Updated April 5, 2023
Introduction to Entity Framework in MVC
The entity framework is related to the ORM Framework. ORM means Object Relational Mapping. ORM automatically creates classes based on the database table and vice versa is also true. We can say it can also automatically generate necessary SQL to create database tables based on classes.
Entity framework is essentially is a persistence framework that frees you from all the extra work. We do not have to write any stored procedures, manage database connections, or manually mapping the database or table to the domain object. The entity framework will do all these. Therefore, if we want to access the database in our application, which we most often used, we used a persistent framework.
Examples of Entity Framework in MVC
Let’s have a more clear understanding of the entity framework in MVC with the help of an example.
Step 1: we need to create an MVC project first and after that, we need to add models. Select a file and click on new and then on the project to create a new project.
Step 2: Provide a name to the project now and click on OK.
Step 3: Now select a template for the project as MVC and click on OK.
Step 4: After clicking ok, visual studio creates a project that has the following structure.
Step 5: Now we need to create a model that will be for the database. Set name as Employee.cs by adding new class. For adding new class right click on the model folder.
Step 6: We have to modify the class with the below code.
Employee.cs
using System;
namespace MvcEntityDemo.Models
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Course { get; set; }
public string Contact { get; set; }
}
}
To coordinate with Entity Framework we need to create a database context class for a given data model. put this class in the folder which is models. now right-click on the folder model and add this class here. we need to give a name that is RecordContext.cs to the class. Now modify the class by the below code.
RecordContext.cs
using MvcEntityDemo.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MvcEntityDemo.Models
{
public class RecordContext : DbContext
{
public RecordContext() : base("RecordContext")
{
}
public DbSet<Employee> Employee { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
Creating Migration
Below are the steps to create a migration.
Go to View then click on other windows and then package managerOpen Package manager console. we need to run the following commands now.
- enable-migrations – ContextTypeName MvcEntityDemo.Models.RecordContext
- In the project, the framework will create a migration folder and the configuration.cs file after the above command is executed. We will update the file with the below code in configuration.cs.
Configuration.cs
namespace MvcEntityDemo.Migrations
{
using MvcEntityDemo.Models;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<MvcEntityDemo.Models.RecordContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed( MvcEntityDemo.Models.RecordContext context )
{
var Employee = new List<Employee>
{
new Employee{ Name="Mohan",Email=" [email protected]",Course="Manual Testing", Contact="+ 25-258628" },
new Employee{ Name=" John",Email=" John example.com",Course="Automation Testing ", Contact="+ 25-258694" },
new Employee{ Name="neha",Email="[email protected]",Course="Big Data", Contact="+ 25-258999" },
new Employee{ Name="Saba",Email="[email protected]",Course="Linux ", Contact="+ 25-258111"},
};
Employee.ForEach( s => context.Employee.Add(s) );
context.SaveChanges();
}
}
}
}
Save the file first and run both the commands now from the package manager console.
- PM> add-migration initial.
- PM> update-database.
We can see the initials created by this command inside the migration folder for the project. We need to create the scaffolding so as to display it on the web page.
After that select and add the scaffold.
Now add a controller and provide its details so as to create a view.
Controller.cs
New EmployeeController is now added and it contains some below auto-generated code.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MvcEntityDemo.Models;
namespace MvcEntityDemo.Controllers
{
public class EmployeeController:Controller
{
private RecordContextdb=new RecordContext();
//GET:Employee
public ActionResultIndex()
{
returnView(db.Employee.ToList());
}
//GET:Employee/Details/5
public ActionResultDetails(int?id)
{
if(id==null)
{
return newHttpStatusCodeResult(HttpStatusCode.BadRequest);
}
EmployeeEmployee=db.Employee.Find(id);
if(Employee==null)
{
returnHttpNotFound();
}
returnView(Employee);
}
//GET:Employee/Create
public ActionResultCreate()
{
return View();
}
//POST:Employee/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResultCreate([Bind(Include="ID,Name,Email,Course,Contact")]EmployeeEmployee)
{
if(ModelState.IsValid)
{
db.Employee.Add(Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Employee);
}
//GET:Employee/Edit/5
public ActionResult Edit(int? id)
{
if(id==null)
{
return newHttpStatusCodeResult(HttpStatusCode.BadRequest);
}
EmployeeEmployee=db.Employee.Find(id);
if(Employee==null)
{
return HttpNotFound();
}
return View(Employee);
}
//POST:Employee/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
publicActionResultEdit([Bind(Include="ID,Name,Email,Course,Contact")]EmployeeEmployee)
{
if(ModelState.IsValid)
{
db.Entry(Employee).State=EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Employee);
}
//GET:Employee/Delete/5
public ActionResultDelete(int?id)
{
if(id==null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee Employee = db.Employee.Find(id);
if(Employee==null)
{
return HttpNotFound();
}
return View(Employee);
}
//POST:Employee/Delete/5
[HttpPost,ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed( int id )
{
Employee Employee = db.Employee.Find(id);
db.Employee.Remove(Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
View folder contains employee folder.It contains auto-generated files like index.
Index file will have below code.
Index.cshtml
@model IEnumerable<MvcEntityDemo.Models.Employee>
@{
ViewBag.Title="Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink( "Create New", "Create" )
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor( model=>model.Name )
</th>
<th>
@Html.DisplayNameFor( model=>model.Email )
</th>
<th>
@Html.DisplayNameFor( model=>model.Course )
</th>
<th>
@Html.DisplayNameFor( model=>model.Contact )
</th>
<th></th>
</tr>
@foreach( var item in Model ){
<tr>
<td>
@Html.DisplayFor( modelItem=>item.Name )
</td>
<td>
@Html.DisplayFor( modelItem=>item.Email )
</td>
<td>
@Html.DisplayFor( modelItem=>item.Course )
</td>
<td>
@Html.DisplayFor( modelItem=>item.Contact )
</td>
<td>
@Html.ActionLink( "Edit", "Edit", new { id=item.ID } ) |
@Html.ActionLink( "Details", "Details", new { id=item.ID } ) |
@Html.ActionLink( "Delete", "Delete", new { id=item.ID } )
</td>
</tr>
}
</table>
To run the code just press ctrl+F5 and it will produce the following output.
Output:
Conclusion
In this article, we got the basic information of what is an entity and how it deals with entity framework with MVC. With the help of an example, it is more clear how to use it and where it is exactly used. From this article, we come to know that the entity framework depends on ORM.
Recommended Articles
This is a guide to the Entity Framework in MVC. Here we also discuss the Introduction of the entity framework along with examples and its code implementation. You may also have a look at the following articles to learn more –