How to Implement Entity Framework in ASP.NET MVC

Introduction

In this article, we are going to learn how to implement an entity framework in ASP.NET MVC. Before proceeding further, I would recommend that you will understand. how to create an ASP.NET MVC Application.

The business objects or entity which is going to act as the model in our MVC application. and if you see the student entity is actually residing. within, the model folder of our MVC application.

Model class

So, we have this following code Student class. with this for auto-implemented properties and within the class.

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string City { get; set; }
} 

Controller

In Student controller class. we’re actually creating an instance of this Student object. and notice that the Student data is actually hard-coded within this controller action method. and then we are passing this Student object to the view for rendering.

public ActionResult Details()
{
    Student student = new Student()
    {
	  Id = 1200,
	  Name = "James"
          Gender = "Male"
          City = "Mexico"
	}	
    return View(student);
}

Data table

But, we actually retrieve the Student data from a database table so here we have the table TblStudent.

Id     Name        Gender   City
-----  -----       ------   ------
5001   James Hoog   Male    Mexico
5002   Nail Knite   Male    Paris    
5005   Pit Alex     Male    London   

Then, we want to retrieve data from this table. and then build our Student model object. and then send that Student model object to the view which will then render that Student.

Let’s see, how to retrieve Student data using entity framework. now, if you remember your models can be either entities or business objects. in this article, we are going to use this Student entity. and we are going to use Entity Framework to retrieve data from this table TblStudent.

Install Entity Framework

The first step is to install the entity framework and the easiest way to do that is by using a new get package manager. so, let’s go to visual studio and click on tools. then, select library package manager and manage the NuGet packages for Solution. so this should open up NuGet package manager.

NuGet Package Manager

It showing all the packages that are away that setup. that is available for installation then we entity framework in our system.

After, the package installation. it should add a reference to that assembly. so, we have entity framework installed on the system. there is a reference added to the entity framework. another step is to add Student context towards .cs class file.

Database Contex class

Let’s, go to the visual studio. so, right click on the model folder Adds a class file. and let’s call this Student context so Studentcontext.cs.

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
    
public partial class Studentcontext : DbContext
{
    public Studentcontext()
    {
    }
    public virtual DbSet<Student> Students { get; set; }
}

The StudentContext.cs class it’s inheriting from another class called DbContext. The DbContext class is actually present in System.Data namespace.

The StudentContext class inheriting from the DBContext base class. the purpose of this class is to actually, establish a connection to our database. so, this table tblStudent is actually present within the sample database.

Is going to establish a connection to our database and it’s deriving from DbContext. the Student context class itself. it has got this property Students a public property which is returning a DB set of Students.

The second step, is we are going to get all the Students. that are present in this table TblStudent and using the property Students. of this StudentContext class.

Define connection string

The third step, if this StudentContext class has to create a connection. it needs to know about the connection string information. the perfect place for connection strings to the web.config file. so, the next step is to actually add a connection string to our web.config file and to the web.config file. that’s presented within the root directory of our MVC application.

The name of the connection string is StudentContext. the name of this connection string matches with the name of our class StudentContext. so, when we create an instance of this class.

It’s going to look for a connection string. with that name within Web.config file. so, we have a connection string there with that name and then it’s going to use this connection string.

So, if you see the connection string. the server start meaning the local installation of SQL server and then the database name is a sample.

We are using Windows authentication the provider name is System.Data.Sqlclient

<connectionStrings>
  <add name="StudentContext" 
        connectionString="server=.; database=Sample; integrated security=SSPI"
        providerName="System.Data.SqlClient"/>
</connectionStrings>
Then, the third step adds a connection string to the web.config file. that’s present in the root directory of your MVC application.

Table mapping to model class

By default that the entity framework is going to look for a table with that name Student. but, then what’s the name of our table it’s actually TblStudent. so, we warned this entity class to map to our table TblStudent so how do we do that mapping using table attribute.

Let’s, go ahead and use the table attribute on this class. the table and then what’s the table to which this class needs to be map TblStudent.

[Table("tblStudent")]
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string City { get; set; }
}

So, we have a compilation error. we need to import the namespace. that this attribute is present in “System.ComponentModel.DataAnnotations.Schema” namespace.

The fifth step, make the required changes to our controller action method. so, at the moment if you look at our controller Student controller action method. we have the Student data hard-coded. there and we don’t want to do that we actually want to retrieve the data from this table tblStudent.

Create Database Instance

The first thing to do is to establish a connection to the database. we added this StudentContext class. so, create an instance of this class which is going to use the connection string. that’s present in the web.config file. create a connection for us. so, let’s do that so StudentContext.

Then remember this class this StudentContext class has got this property Students. so, StudentContext.Students property which is going to return the list of Students. all the Students that the DB set of Students that’s present in this table. but, remember what we want to do is we don’t want all Student details we want one Student detail.

Here, we want to get the specific Student details. at the moment controller action method. we are going to pass in a parameter with name ID. which is going to be the Student ID. for, we need the information so we are going to filter the Students based on the ID that comes into this controller action method.

public ActionResult Details(int id)
{
    StudentContext StudentContext = new StudentContext();
    Student student = StudentContext.Student.Single(x => x.StudentId == id);

    return View(student);
}

It’s going to return a single Student object. so, we are going to store that within this object reference variable in Entity Framework.

Initializer Database

The application_start event handler. which gets executed at the beginning. the application first starts. and then here we going to invoke and set initializer method of Database class. again this database class is present in system.data.entity namespace. so, let’s go ahead and import that so what is the set initializer function going to do.

Database.SetInitializer<MVCDemo.Models.EmployeeContext>(null);

We are actually using this database sample. the database is an existing database. so, we have the table TblStudent, which has got already some sample data. now, set in each initializer function.

The initialize our database. if you don’t have the database already created. it’s going to create a database for you. create tables for you and populate them with some sample data but then we already have you know the database the tables. and the data so we don’t want any initialization strategy so for our Student context object.

We passing nulls specifying that. we don’t want to have any database initialization strategy. so, that’s the importance of this line. the changes that require. so, let go and run this application.

The Student property is going to return the database set of Students. but, then out of them we only want the Student whose ID is 5001. we are filtering here using the single LINQ method. which is going to return the Student with ID 5001 which is then passed to this view.

So, we get James’s record all from database resource.

asp.net mvc output table

Thanks for the Reading article! I hope this get’s you started MVC Application. Take care.

Leave a Reply

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