Code First Approach in Entity Framework in Asp.net MVC with Example

  Total Views : 3035
  Comments : 0
 
  Keywords : How to use code first approach in entity framework in asp.net mvc, Mvc application using code entity framework first approach, Code first in entity framework example in asp.net mvc

In asp.net mvc Code First approach in entity framework is used to write POCO classes first and according to that the database will be created. We will learn entity framework code first approach with simple example in asp.net mvc. 

 

Let's start with creating new asp.net mvc 4 application for that Open visual studio studio à Go to File à Select New à Select Project 

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# àinside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “MVCcodefirst” then finally click on ok button

 

Create code first approach in entity framework in asp.net mvc application

 

After naming it just click on OK now new dialog will pop up for selecting template in that Select Empty template and click ok like as shown below 

 

select template for code first entity framework asp.net mvc application

 

After selecting Empty template now we are going to add Entity framework.

Installing Entity Framework in Asp.Net MVC Applicaiton

For adding Entity framework just right click on your application and from list select “Manage NuGet Packages”. After select a new dialog will popup for “Manage NuGet Packages” inside search box enter “Entityframework”. After getting search value select Entityframework click on install button 

 

Installing Entity Framework in Asp.net mvc application

 

After adding it will show an ok sign in green color

 

After install entity framework in asp.net mvc application

 

After completing adding Entityframework now it’s time to add POCO Classes.

Adding POCO Classes

Now let’s add a POCO Classes (Plain old CLR object) and start defining as per your model requirement. For adding POCO Classes just Right click on Model folder à select Add à then select Class and Name the class as EmployeeDetails. Once we add EmployeeDetails class file in Model folder our project structure like as shown below 

 

POCO Class in Model Folder in asp.net mvc application

 

Now open EmployeeDetails class file and write the code like as shown below. Here if you observe we used DataAnnotations (Key) for uniquely identify entity

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace MVCCodefirst.Models

{

public class EmployeeDetails

{

[Key]

public int EmpID { get; set; }

public string Name { get; set; }

public string Address { get; set; }

public Nullable<int> Age { get; set; }

public Nullable<decimal> Salary { get; set; }

public string worktype { get; set; }

}

}

Adding Connection string in Web.config

We are going to add connection string in Web.config because we need to tell it where to create Database that would be like as shown below 

 

<connectionStrings>

<add name="DefaultConnectionproviderName="System.Data.SqlClientconnectionString="data source=sai-pc;

initial catalog=MVCCodeFirst; persist security info=True; user id=sa; password=#######; App=EntityFramework" />

</connectionStrings>

DefaultConnection - Connection string name we used above. Using this Code-first will create “MVCCodeFirst” as database name in the local sql server. You can give any unique name to database which ever you want to create.

Adding DbContext

Generally DbContext is the primary class that is responsible for interacting with data as object, which includes change tracking, persisting data, managing relationship, caching ,querying to the database. DbContext works as a bridge between your domain or entity classes and the database. Here we created a Class with Name “EmployeeDetailsContext” and folder structure after adding EmployeeDetailsContext class

 

Adding dbcontext file in asp.net mvc application

 

Our EmployeeDetailsContext file will contain code like as shown below 

 

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace MVCCodefirst.Models

{

public class EmployeeDetailsContext

{

 

}

}

Now we will make modification to EmployeeDetailsContext file by inheriting from DbContext class and included Dbset of Model name (EmployeeDetails) that will be like as shown below

 

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace MVCCodefirst.Models

{

public class EmployeeDetailsContext : DbContext

{

public EmployeeDetailsContext() : base("DefaultConnection")

{

 

}

public DbSet<EmployeeDetails> EmployeeDetails { get; set; }

}

}

Find below details for properties whatever we add in above context file

 

base("DefaultConnection") - Constructs a new context instance using the given string as the name or connection string for the database to which a connection will be made.

 

DefaultConnection - Is the name of connection string which we have passed.

 

Lastly we added Dbset of Model name (EmployeeDetails) which we created in Models folder

 

public DbSet<EmployeeDetails> EmployeeDetails { get; set; }

In future if you are going to add more Model then you need to make change in EmployeeDetailsContext class by adding more Dbset. Now let's test how it works. For that we need to create controller

Adding Controller

To add controller Just Right click on Controller Folder inside that select Add and then select Controller. After new pop up will open in that mention Controller name as "Default1Controller" and select template as "Empty MVC Controller" then click Add. Once we add now open our controller from folder and write the code like as shown below

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using MVCCodefirst.Models;

 

namespace MVCCodefirst.Controllers

{

public class Default1Controller : Controller

{

//

// GET: /Default1/

 

public ActionResult Index()

{

using (var context = new EmployeeDetailsContext())

{

List<EmployeeDetails> Employeelist = context.EmployeeDetails.ToList();

}

return View();

}

}

}

Now you can have a look on Local sql server you will not find MVCCodeFirst database once we run application and access Default controller then the Database will be created and it will get you records from that database. 

 

Code first approach entity framework in asp.net mvc application

After that it is going to query database for getting records from Table EmployeeDetails below is the debug snapshot while getting data. It has got zero count because we do not have records in that table.

 

Getting records from database using code first entity framework approach in asp.net mvc application

 

This way we will use entity framework code first approach in asp.net mvc applications. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User