Entity Framework in ASP.NET MVC

Entity Framework in ASP DOT NET MVC

The controller responds to URL request, gets the data from a model and hands it over to the view. The view then renders the data. The model can be entities or business objects. In this article, we will discuss retrieving the data from a database using entity framework database first approach. In a later article, we will discuss using business objects as our model. Let’s see how to use Entity Framework in ASP DOT NET MVC application.

Use below SQL Script to create Database MVC_DB, Table Employee and populate Employee table with some test data:
--Create a database called MVC_DB
CREATE DATABASE MVC_DB
GO

--Use MVC_DB
USE MVC_DB
GO

--Create a Table called Employee
CREATE TABLE Employee
(
  EmployeeId int Primary Key Identity(1,1),
  Name nvarchar(50),
  Gender nvarchar(10),
  City nvarchar(50),
  Salary decimal(18,2)
)
GO

--Insert some values into Employee Table
INSERT INTO Employee values('Pranaya','Male','Mumbai', 2000)
INSERT INTO Employee values('Sambit','Male','Chennai', 3000)
INSERT INTO Employee values('Priyanka','Female','Hydrabad', 4000)
INSERT INTO Employee values('Anurag','Male','Cheenai', 4000)
INSERT INTO Employee values('Subrat','Male','Mumbai', 3000)
INSERT INTO Employee values('Preety','Female','Mumbai', 2000)
INSERT INTO Employee values('Trupti','Female','Hyderabad', 5000)
GO
Step 1: Create Empty MVC project called CRUD_OperationsInMVC

First of all, open Visual Studio 2013 (you can also use any higher version of visual studio) and click on a New Project link in the Startup page as shown below. Alternatively, you can also select File menu -> New Project.

Entity Framework in ASP DOT NET MVC - Start

From the New Project dialog as shown below, expand the Visual C# node and select Web in the left pane, and then select ASP.NET Web Application in the middle pane. Name your project as CRUD_OperationsInMVC. (You can give an appropriate name for your application). Also, you can change the location of the MVC application by clicking on the Browse button. Finally, click OK as shown in the below image.

Entity Framework in ASP DOT NET MVC - Create project

Once you click on the OK button a new dialog will pop up with Name “New ASP.NET Project” for selecting project Templates as shown below.

Entity Framework in ASP DOT NET MVC - Select Template

In this dialog, we are going to choose Empty project template and Select MVC from Add Folders and core reference section.

You can also change the authentication by clicking on Change Authentication button. You can select appropriate authentication mode for your application. Here, we are not going to have any authentication for our application. So select No Authentication radio button and click OK. (By default, Individual User Accounts would be selected to authenticate users stored in SQL Server database.)

Entity Framework in ASP DOT NET MVC - Change Authentication

Wait for some time till Visual Studio creates a simple MVC project using the default template.

Step 2: Add ADO.NET Entity Data Model to our project

Right Click on Models Folder => Add => New Item

Select Installed => Visual C# => Data

Select ADO.NET Entity Data Model from the Templates

Provide the name as EmployeeDataModel

Click on Add button as shown below

Entity Framework in ASP DOT NET MVC - Add ADO.NET Entity Data Model

From the next screen Select EF Designer from Database from Entity Data Model Wizard and click on Next button as shown below

Entity Framework in ASP DOT NET MVC - Select Entity Model

In the next step, click on new connection From Choose your data connection wizard as shown below

Entity Framework in ASP DOT NET MVC - Choose Data Connection

Provide the necessary details to communicate with the database

Provide the Server name

Select the Authentication Type

Select the Database

Click on the Ok button as shown below

Entity Framework in ASP DOT NET MVC - Connection Properties

Then provide a meaningful name for the connection string that is going to save in the web.config file, here I am naming the connection string as EmployeeDBContext and click on Next button as shown below.

Entity Framework in ASP DOT NET MVC - Connection String

Next, we need to select the version of Entity Framework

Here I am going to use Entity Framework 6.x so I am selecting Entity Framework 6.x radio button and click on Next button as shown below

Entity Framework in ASP DOT NET MVC - Select EF Version

Select the Database Objects

In this step, we need to select the database object for our application. Here we need to select Employee Table

Give a meaningful namespace where our EDMX file needs to be generated

Click on Finish button as shown below

Entity Framework in ASP DOT NET MVC - Choose database objects

Once you click on the Finish button, let’s see what the things are created by Entity Framework

It will add the reference to the Entity Framework in the reference folder

Entity Framework in ASP DOT NET MVC - Reference Folder

The framework will create the EDMS file within the Models folder

Entity Framework in ASP DOT NET MVC - EDMX Folder

It will create the Employee Model.

To see the Employee Model click on Employee.cs file, this is inside the EmployeeDataModel.tt File

namespace CRUD_OperationsInMVC.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public Nullable<decimal> Salary { get; set; }
    }
}

It will create the connection string in web.config file as shown below

Entity Framework in ASP DOT NET MVC - CS

It will create the DBContext class for us whose name is the same as the name of the connection string that is EmployeeDBContext

EmployeeDBContext class derives from DbContext class and is responsible for establishing a connection to the database

Filename: EmployeeDataModel.Context.cs which is inside EmployeedataModel.Context.tt as sown below

Entity Framework in ASP DOT NET MVC - Context Class

Below is the auto-generated code for the EmployeeDBContext class
namespace CRUD_OperationsInMVC.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class EmployeeDBContext : DbContext
    {
        public EmployeeDBContext()
            : base("name=EmployeeDBContext")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Employee> Employees { get; set; }
    }
}

That’s it. We successfully created our Entity Data Model. Now it’s the time to use this model in our application.

Let’s create a controller called EmployeeController

Right Click on Controller Folder. Select Add => Controller => Select MVC5 Controller Empty => Click on add button as shown below

Entity Framework in ASP DOT NET MVC - Adding Controller

In the next Screen provide the controller name as EmployeeController and click on add button as shown below

Entity Framework in ASP DOT NET MVC - Naming Controller

Let’s modify the default route in the RouteConfig class so that when the application runs for the first time it will redirect to the Index Action method of Employee Controller

After modifying the RouteConfig class the codes looks like as shown below

namespace CRUD_OperationsInMVC
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
Let’s modify the index action method of employee controller to use entity framework as shown below
namespace CRUD_OperationsInMVC.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeDBContext dbContext = new EmployeeDBContext();
            List<Employee> empList = dbContext.Employees.ToList();
            return View(empList);
        }
    }
}
Let’s create the index view.

Right-click on the Index Action Method and click on Add View. Then paste the following code in the Index View

@model IEnumerable<CRUD_OperationsInMVC.Models.Employee>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Salary)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Salary)
        </td>
    </tr>
}
</table>

That’s it. Run the application and see the result as expected.

Entity Framework in ASP DOT NET MVC

In this article, we just see how to use Entity Framework in ASP DOT NET MVC Application step by step. In our upcoming articles, we will discuss how to perform CRUD operations in ASP.NET MVC using Entity Framework with real time example.

In the next article, I will discuss how to create Hyperlink in ASP.NET MVC application.

SUMMARY
In this article, I try to explain how to use Entity Framework in ASP DOT NET MVC application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *