Wednesday, February 11, 2015

Model First Approach to Database Connectivity in ASP.NET MVC 5

As a developer, you must be aware that the Entity Framework makes available several ways for you to make a connection between the database and the ASP.NET web application. The three most popular ways include:

  • Code First Approach
  • Database First Approach
  • Model First Approach
All these approaches have their own set of benefits. However, in this post, we are going to focus on the Model First Approach using the Entity Framework 6. and this is how we will establish the connection between the application and database.

The MVC Project Template will be used to create the ASP.NET web application.

A Brief About Entity Framework 6

Entity framework is a versatile framework that serves a slew of purposes and makes our job more streamlined and effective. The features that intrigue us most include:
  • Async Query and Save
  • Connection Resiliency
  • Code Based Configuration
  • Dependency Resolution
  • Multiple Contexts per Database
Getting Down to Some Action

We will begin with creating the MVC 5 application and for it, we will make use of the Model First Approach. The sequence of steps involved here are:
  • Creating the Web Application
  • Including the Entity Data Model
  • Bringing into play the Entity Data Model Designer
  • Getting involved with Controller and Views
  • Perform the CRUD Operations
  • Work with the Database
Let's Create the Web Application

Let us use the MVC Project Template to build our ASP.NET web application:
  • Open Visual Studio 2013 and click on New Project.
  • Head to the left tab and in there, select the Web tab, followed by selection of the ASP.NET web application. Name the application as "MvcBook"
ASP Net web application

On the next screen, select MVC Project Template and then click on ok.
MVC project template
Here, Visual Studio has automatically created an MVC application, along with adding a number of files and folders to your project. The Solution Explorer clearly shows the same.

Adding the Entity Data Model

The next step is adding the ADO.NET Entity Data Model to the application and the process will be begun by creating an empty model and then proceed with the following:

Head to the Solution Explorer and in there, right-click on the Models folder. Then, click the label, “ADO.NET Entity Model”
ADO NET entity data model
Then open the new Entity Model Wizard and in there, go for the Empty Model.
Empty model
Once that is done, the Entity Model Designer will be visible to you.
Entity model designer

Let's Work with Entity Data Model Designer

We now have to add an entity in the Entity Data Model Designer, and we will be addressing the sections, “Adding Entity Model” and “Generating Database from Model”.

Let's first add the entity model for which we will create the same.

Step 1: We first right-click on Data Model Designer and then add new entity.
New entity
Step 2: Then we give our entity a name in the next screen
Entity name
Step 3: With our entity now created, we will assign a scalar property to it, which can simple be done by right-clicking on it and then choosing to add the new scalar property.
We will now change the property name
Property name

Step 4: Add more scalar property
Scalar properties

Generating Database from Model

One thing that you ought to know that we also have the freedom to create additional entity models in the Data Model Designer. With that understanding, we will proceed to generating the database from the model.

Step 1: When we right-click on the Data Model Designer, we get a menu from which we will select the Generate Database from Model.
Step 2: On the next screen, we'll click on New Connection to establish a connection with the database.
New connection
Step 3: We now move on to the new Connection Properties wizard where we will assign names to the server name and the database as well.
Server and database names
Step 4: Moving on to the Generate Database Wizard, the connection just created is visible and so, click on the Next button.
Step 5: Then follows the generation of database summary and script.
Database summary
Step 6: We'll now right click on the script which gives us an option to execute it. Click on Execute
Once the execution is accomplished, we have a new database with us and this can be seen in the Server Explorer.
New database

Working with Controller and Views

And now we proceed to bringing the controller and views in MVC 5 in action. . The MVC 5 controller will be added and then Entity Framework will be used to view.

Step 1: For starters, the solution is build, and once that is done, we can see the model class in the Models folder.
In the models folder, we also see the Book class being generated. We now will modify the code with our code below:

namespace MvcBook.Models
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    public partial class Book
        public int Id { get; set; }
        public string Name { get; set; }
        public string Genre { get; set; }
        [Display(Name="Release Date")]
        public System.DateTime ReleaseDate { get; set; }

In the code above, Data Annotation is implemented so that we can change the property name that is displayed and also the date at which the property was initialized.

Step 2: Let's go back to the Solution Explorer and in there, make a right-click on the Controller. Then, Add New Scaffolded Item.
Step 3: In that wizard, we will use the Entity Framework with Views to select the MVC 5 Controller.
MVC 5 controller
Step 4: Next stop is to assign a name to the controller, choose model class, the Data Context class. Once the selections are done, click on Add.
Controller model data
Upon clicking on Add, the BookController class swings into action in the Controllers folder. Also, the Book folder gets generated in the Views folder.
Book folder

Perform the CRUD Operations

And now, we move on to performing the CRUD (Create, Read, Update and Delete) operations.
To begin so, we will initiate an Action Link to our View. It can be done from Views->Shared->_Layout.cshtml file. The code will be modified like this:

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Book App</title>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                @Html.ActionLink("Best Books", "Index", "Home", null, new { @class = "navbar-brand" })
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.ActionLink("Books", "Index", "Book")</li>
    <div class="container body-content">
        <hr />
            <p>© @DateTime.Now.Year - My Book Application</p>
    @RenderSection("scripts", required: false)


Now, we will start performing the CRUD operation.

Step 1: The application first has to be made to run on the application's homepage and then, we click on Books.
Step 2: The window that appears next, we will click on the Create New link in order for the new record to be created

Step 3: This is how we will add the record:
Create new


Now, at every instance of clicking on the Books link, the respective records can be easily read


We can update the corresponding record using the following procedure.

Step 1: With the record you have, Click on the Edit link.
Edit record

Step 2: Now, make the necessary edits to the record and hit the Save button.
Save record


The Delete Link offers you a simple enough way to delete the record.
Delete record

Working with Database

All the tables and the records we have created will be integrated into the database. And Server Explorer will let us explore the database

Step 1: First, head to the Server Explorer and open the model

Step 2: Now, click on the Tables folder and in there, make a right-click on the table. Then, click on the Show Table Data.
Show table data

Step 3: The records will display on the screen.
Records displayed

And thus, we have successfully applied the Model First Approach to establish a connection with the database while making use of the different operations on our course. Hope you find this tutorial useful and easy to follow. Do give us your inputs in the comments below.

About the Author:

Celin Smith is serving as a web developer at Xicom Technologies Ltd- A renowned .NET Development Outsourcing Services Company. If you are looking for Hire ASP.NET Developer you can contact her via Facebook and Linkedin. She has also written interesting and informative articles on Custom Software Development, Web Application Development etc.

0 comentarios:

Post a Comment