CRUD Using ASP.NET MVC 5 And Entity Framework

Introduction

 
In this article we will learn how to perform Create, Read, Update, and Delete Operations in ASP.NET MVC 5 using the Entity Framework Code First Approach. The source code can be downloaded from: https://github.com/KhajaMoizUddin/CRUD-MVC5-EntityFramework
 
In this project, I am working with Visual Studio 2019. In order to create a new MVC Project, follow these steps:
 
Click on Create a New Project, under templates select ASP.NET Web Application(.Net Framework C#) then click on Next.
 
Provide the application name for example: CRUDMVCEF and provide the location where you want to save the application and click on create.
 
From create a new ASP.NET Web Application, select MVC template and click on Create.
 
With this a new MVC Project will be created, as shown in the below images.
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
Right click on Models folder and add three classes and rename the classes as Employee.cs and Department.cs and EmployeeDbContext.cs.
 
Here Employee.cs and Department table contains the fields or properties for the creation of Employee and Department tables.
 
Open Employee.cs and paste the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace MVCCRUDProject.Models  
  8. {  
  9.     public class Employee  
  10.     {  
  11.   
  12.         [Key]  
  13.         public int EmployeeId { getset; }  
  14.         [Display(Name = "Employee Name")]  
  15.         public string EmployeeName { getset; }  
  16.         [Display(Name = "Designation")]  
  17.         public string EmployeeDesignation { getset; }  
  18.         public Department Department { getset; }  
  19.         [Display(Name = "Address")]  
  20.         public string EmployeeAddress { getset; }  
  21.         [Display(Name = "Passport")]  
  22.         public string EmployeePassport { getset; }  
  23.         [Display(Name = "Phone")]  
  24.         public int EmployeePhone { getset; }  
  25.         [Display(Name = "Gender")]  
  26.         public string EmployeeGender { getset; }  
  27.         [Display(Name = "City")]  
  28.         public string City { getset; }  
  29.         [Display(Name="Project")]  
  30.         public string Project { getset; }  
  31.         [Display(Name="Company Name")]  
  32.         public string CompanyName { getset; }  
  33.         [Display(Name = "Pin Code")]  
  34.         public int PinCode { getset; }  
  35.         [Display(Name = "Dept Name")]  
  36.         public int DepartmentId { getset; }  
  37.     }  
  38. }  
Open the Department.cs and paste the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace MVCCRUDProject.Models  
  8. {  
  9.     public class Department  
  10.     {  
  11.         [Key]   
  12.         public int DepartmentId { getset; }  
  13.   
  14.         public string DepartmentName { getset; }  
  15.     }  
  16. }  
Similarly Open the EmployeeDbContext.cs and paste the below code. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Security.AccessControl;  
  6. using System.Threading;  
  7. using System.Web;  
  8.   
  9. namespace MVCCRUDProject.Models  
  10. {  
  11.     public class EmployeeDbContext : DbContext  
  12.     {  
  13.         public EmployeeDbContext()  
  14.         {  
  15.   
  16.         }  
  17.   
  18.         public DbSet<Employee> Employee { getset; }  
  19.         public DbSet<Department> Department { getset; }  
  20.     }  
  21. }  
Now add the Entity Framework, by right clicking on the references and clicking on Manage Nuget Packages. Browse to the Entity Framework and click on install as
shown in the below image. As I have already installed it, it's shown as uninstall. In your case it will be showing as install.
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
Now Navigate to Tools --> Nuget Package Manager -->Package Manager Console and execute the following commands
 
PM> Enable-Migrations
 
With the above command, a new Migrations folder will be created with Configuration.cs class file.
 
PM> Add-Migration 'EmployeeDepartmentModels'
 
With the above command a new Migration 'EmployeeDepartmentModels' class will be created with the following code. The below code contains the creation of both Employee and Department table with Primary key and Foreign key.
  1. namespace MVCCRUDProject.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity.Migrations;  
  5.       
  6.     public partial class EmployeeDepartmentModels : DbMigration  
  7.     {  
  8.         public override void Up()  
  9.         {  
  10.             CreateTable(  
  11.                 "dbo.Departments",  
  12.                 c => new  
  13.                     {  
  14.                         DepartmentId = c.Int(nullable: false, identity: true),  
  15.                         DepartmentName = c.String(),  
  16.                     })  
  17.                 .PrimaryKey(t => t.DepartmentId);  
  18.               
  19.             CreateTable(  
  20.                 "dbo.Employees",  
  21.                 c => new  
  22.                     {  
  23.                         EmployeeId = c.Int(nullable: false, identity: true),  
  24.                         EmployeeName = c.String(),  
  25.                         EmployeeDesignation = c.String(),  
  26.                         EmployeeAddress = c.String(),  
  27.                         EmployeePassport = c.String(),  
  28.                         EmployeePhone = c.Int(nullable: false),  
  29.                         EmployeeGender = c.String(),  
  30.                         City = c.String(),  
  31.                         Project = c.String(),  
  32.                         CompanyName = c.String(),  
  33.                         PinCode = c.Int(nullable: false),  
  34.                         DepartmentId = c.Int(nullable: false),  
  35.                     })  
  36.                 .PrimaryKey(t => t.EmployeeId)  
  37.                 .ForeignKey("dbo.Departments", t => t.DepartmentId, cascadeDelete: true)  
  38.                 .Index(t => t.DepartmentId);  
  39.               
  40.         }  
  41.           
  42.         public override void Down()  
  43.         {  
  44.             DropForeignKey("dbo.Employees""DepartmentId""dbo.Departments");  
  45.             DropIndex("dbo.Employees"new[] { "DepartmentId" });  
  46.             DropTable("dbo.Employees");  
  47.             DropTable("dbo.Departments");  
  48.         }  
  49.     }  
  50. }  
PM> Update-Database
 
When we execute the above Update command, the above code is used for the creation of Employee and Department tables in the database. And a new file with name
ProjectName.Models.EmployeeDbContext.mdf file will be created under App_Data.
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
In order to Insert the data to these tables run the below command. 
 
PM> Add-Migration 'UpdateDepartmentData'
 
With the above Command, UpdateDepartmentData class will be created with Up() and Down() methods.
 
In the Up() method of UpdateDepartmentData update the code as shown below.
  1. namespace MVCCRUDProject.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity.Migrations;  
  5.       
  6.     public partial class UpdateDepartmentData : DbMigration  
  7.     {  
  8.         public override void Up()  
  9.         {  
  10.             Sql("Insert into Departments(DepartmentName)Values('IT')");  
  11.             Sql("Insert into Departments(DepartmentName)Values('HR')");  
  12.             Sql("Insert into Departments(DepartmentName)Values('Payroll')");  
  13.             Sql("Insert into Departments(DepartmentName)Values('Talent Acquisition')");  
  14.             Sql("Insert into Departments(DepartmentName)Values('Training & Development')");  
  15.         }  
  16.           
  17.         public override void Down()  
  18.         {  
  19.         }  
  20.     }  
  21. }  
PM> Update-Database
 
With the execution of the above command, the above Sql Statements or records will be inserted into the Department Table.
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
Similarly, to insert the records into the Employee Table use the following commands
 
PM> Add-Migration 'UpdateEmployeeData'
 
With this a new UpdateEmployeeData class will be created like below.
  1. namespace MVCCRUDProject.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity.Migrations;  
  5.       
  6.     public partial class UpdateEmployeeData : DbMigration  
  7.     {  
  8.         public override void Up()  
  9.         {  
  10.             Sql("Insert into Employees(EmployeeName,EmployeeDesignation,EmployeeAddress,EmployeePassport,EmployeePhone,EmployeeGender,City,Project,CompanyName,PinCode,DepartmentId)" +  
  11.                 "Values('KM','S.E','Hyderabad','K849271',123456789,'Male','Hyderabad','Automation','Infosys',500045,1)");  
  12.         }  
  13.           
  14.         public override void Down()  
  15.         {  
  16.         }  
  17.     }  
  18. }  
Update the code in the Up() method with the number of records you want to insert into the Employee Table.
 
PM> Update-Database
 
With the above command the new records will be inserted into the Employee Table.
 
In order to work with the CRUD Operations, right click on Controllers folder and click on Add Controller and select MVC 5 Controller-Empty and click on Add and rename the
EmployeeController.cs and Add.
 
Open the EmployeeController.cs file and place the below code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using MVCCRUDProject.Models;  
  8. using MVCCRUDProject.ViewModels;  
  9.   
  10. namespace MVCCRUDProject.Controllers  
  11. {  
  12.     public class EmployeeController : Controller  
  13.     {  
  14.         private readonly EmployeeDbContext _dbContext;  
  15.   
  16.         public EmployeeController()  
  17.         {  
  18.             this._dbContext = new EmployeeDbContext();  
  19.         }  
  20.         // GET: Employee  
  21.         public ActionResult Index()  
  22.         {  
  23.             var employeeList = this._dbContext.Employee.Include(x=>x.Department).ToList();  
  24.             return View(employeeList);  
  25.         }  
  26.   
  27.         public ActionResult AddEmployees()  
  28.         {  
  29.             var employeeViewModel = new EmployeeViewModel()  
  30.             {  
  31.                 Department = this._dbContext.Department.ToList(),  
  32.                 Employee = new Employee()  
  33.             };  
  34.             return View("EmployeeForm", employeeViewModel);  
  35.         }  
  36.   
  37.         public ActionResult Edit(int id)  
  38.         {  
  39.             var employees = this._dbContext.Employee.FirstOrDefault(x => x.EmployeeId == id);  
  40.             var department = this._dbContext.Department.ToList();  
  41.   
  42.             var viewModel = new EmployeeViewModel()  
  43.             {  
  44.                 Department = department,  
  45.                 Employee = employees  
  46.             };  
  47.             return View("EmployeeForm", viewModel);  
  48.         }  
  49.   
  50.         [HttpPost]  
  51.         public ActionResult Save(Employee employee)  
  52.         {  
  53.             if (!ModelState.IsValid)  
  54.             {  
  55.                 return RedirectToAction("AddEmployees""Employee");  
  56.             }  
  57.   
  58.             if (employee.EmployeeId == 0)  
  59.                 this._dbContext.Employee.Add(employee);  
  60.   
  61.             else  
  62.             {  
  63.                 var employeesDb = this._dbContext.Employee.FirstOrDefault(x => x.EmployeeId == employee.EmployeeId);  
  64.                 employeesDb.EmployeeName = employee.EmployeeName;  
  65.                 employeesDb.EmployeeDesignation = employee.EmployeeDesignation;  
  66.                 employeesDb.EmployeeAddress = employee.EmployeeAddress;  
  67.                 employeesDb.EmployeePassport = employee.EmployeePassport;  
  68.                 employeesDb.EmployeePhone = employee.EmployeePhone;  
  69.                 employeesDb.EmployeeGender = employee.EmployeeGender;  
  70.                 employeesDb.City = employee.City;  
  71.                 employeesDb.Project = employee.Project;  
  72.                 employeesDb.CompanyName = employee.CompanyName;  
  73.                 employeesDb.PinCode = employee.PinCode;  
  74.                 employeesDb.DepartmentId = employee.DepartmentId;  
  75.             }  
  76.   
  77.             this._dbContext.SaveChanges();  
  78.             return RedirectToAction("Index""Employee");  
  79.         }  
  80.   
  81.         public ActionResult Delete(int id)  
  82.         {  
  83.             var employeeDb = this._dbContext.Employee.FirstOrDefault(x => x.EmployeeId == id);  
  84.             this._dbContext.Employee.Remove(employeeDb);  
  85.             this._dbContext.SaveChanges();  
  86.   
  87.             return RedirectToAction("Index""Employee");  
  88.         }  
  89.     }  
  90. }  
In Views Folder, add a new folder as Employee and add two Views or .cshtml file as EmployeeForm.cshtml and Index.cshtml under Employee folder.
 
Open Index.cshtml add place the below code.
  1. @model IEnumerable<MVCCRUDProject.Models.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Employee Details</h2>  
  8. <hr/>  
  9.   
  10. <button class="">@Html.ActionLink("Add Employees""AddEmployees","Employee")</button>  
  11.   
  12.   
  13. <table class="table">  
  14.     <thead>  
  15.         <tr>  
  16.             <th>@Html.DisplayNameFor(m => m.EmployeeName)</th>  
  17.             <th>@Html.DisplayNameFor(m => m.EmployeeDesignation)</th>  
  18.             <th>@Html.DisplayNameFor(m => m.EmployeeAddress)</th>  
  19.             <th>@Html.DisplayNameFor(m => m.EmployeePassport)</th>  
  20.             <th>@Html.DisplayNameFor(m => m.EmployeePhone)</th>  
  21.             <th>@Html.DisplayNameFor(m => m.EmployeeGender)</th>  
  22.             <th>@Html.DisplayNameFor(m => m.City)</th>  
  23.             <th>@Html.DisplayNameFor(m => m.Project)</th>  
  24.             <th>@Html.DisplayNameFor(m => m.CompanyName)</th>  
  25.             <th>@Html.DisplayNameFor(m => m.PinCode)</th>  
  26.             <th>@Html.DisplayNameFor(m => m.DepartmentId)</th>  
  27.         </tr>  
  28.     </thead>  
  29.       
  30.   
  31.     <tbody>  
  32.     @foreach (var employees in Model)  
  33.     {  
  34.         <tr>  
  35.             <td>@employees.EmployeeName</td>  
  36.             <td>@employees.EmployeeDesignation</td>  
  37.             <td>@employees.EmployeeAddress</td>  
  38.             <td>@employees.EmployeePassport</td>  
  39.             <td>@employees.EmployeePhone</td>  
  40.             <td>@employees.EmployeeGender</td>  
  41.             <td>@employees.City</td>  
  42.             <td>@employees.Project</td>  
  43.             <td>@employees.CompanyName</td>  
  44.             <td>@employees.PinCode</td>  
  45.             <td>@employees.Department.DepartmentName</td>  
  46.             <td>@Html.ActionLink("Edit","Edit"new {id = employees.EmployeeId})</td>  
  47.             <td>@Html.ActionLink("Delete","Delete"new {id= employees.EmployeeId})</td>  
  48.         </tr>  
  49.     }  
  50.     </tbody>  
  51. </table>  
Similarly, open the EmployeeForm.cshtml and place the below code.
  1. @model MVCCRUDProject.ViewModels.EmployeeViewModel  
  2. @{  
  3.     ViewBag.Title = "EmployeeForm";  
  4. }  
  5.   
  6.   
  7. <h2>Employee Details</h2>  
  8. <hr />  
  9.   
  10.   
  11. @using (@Html.BeginForm("Save""Employee"))  
  12. {  
  13.     <div class="form-group">  
  14.         @Html.LabelFor(m => m.Employee.EmployeeName)  
  15.         @Html.TextBoxFor(m => m.Employee.EmployeeName, new { @class = "form-control" })  
  16.     </div>  
  17.   
  18.     <div class="form-group">  
  19.         @Html.LabelFor(m => m.Employee.EmployeeDesignation)  
  20.         @Html.TextBoxFor(m => m.Employee.EmployeeDesignation, new { @class = "form-control" })  
  21.     </div>  
  22.   
  23.     <div class="form-group">  
  24.         @Html.LabelFor(m => m.Employee.EmployeeAddress)  
  25.         @Html.TextBoxFor(m => m.Employee.EmployeeAddress, new { @class = "form-control" })  
  26.     </div>  
  27.   
  28.     <div class="form-group">  
  29.         @Html.LabelFor(m => m.Employee.EmployeePassport)  
  30.         @Html.TextBoxFor(m => m.Employee.EmployeePassport, new { @class = "form-control" })  
  31.     </div>  
  32.   
  33.     <div class="form-group">  
  34.         @Html.LabelFor(m => m.Employee.EmployeePhone)  
  35.         @Html.TextBoxFor(m => m.Employee.EmployeePhone, new { @class = "form-control" })  
  36.     </div>  
  37.   
  38.     <div class="form-group">  
  39.         @Html.LabelFor(m => m.Employee.EmployeeGender)  
  40.         @Html.TextBoxFor(m => m.Employee.EmployeeGender, new { @class = "form-control" })  
  41.     </div>  
  42.   
  43.     <div class="form-group">  
  44.         @Html.LabelFor(m => m.Employee.City)  
  45.         @Html.TextBoxFor(m => m.Employee.City, new { @class = "form-control" })  
  46.     </div>  
  47.   
  48.     <div class="form-group">  
  49.         @Html.LabelFor(m => m.Employee.Project)  
  50.         @Html.TextBoxFor(m => m.Employee.Project, new { @class = "form-control" })  
  51.     </div>  
  52.   
  53.     <div class="form-group">  
  54.         @Html.LabelFor(m => m.Employee.CompanyName)  
  55.         @Html.TextBoxFor(m => m.Employee.CompanyName, new { @class = "form-control" })  
  56.     </div>  
  57.   
  58.     <div class="form-group">  
  59.         @Html.LabelFor(m => m.Employee.PinCode)  
  60.         @Html.TextBoxFor(m => m.Employee.PinCode, new { @class = "form-control" })  
  61.     </div>  
  62.   
  63.     <div class="form-group">  
  64.         @Html.LabelFor(m => m.Employee.DepartmentId)  
  65.         @Html.DropDownListFor(m => m.Employee.DepartmentId, new SelectList(Model.Department, "DepartmentId""DepartmentName"), "Select Department"new { @class = "form-control" })  
  66.     </div>  
  67.   
  68.     @Html.HiddenFor(m => m.Employee.EmployeeId)  
  69.   
  70.     var c = @Model.Employee.EmployeeId > 0 ? "Update" : "Save";  
  71.     <button type="submit" class="btn btn-primary">@c</button>  
  72. }  
Here in the above code for declaration we used ViewModel as we are using Employee and Department properties.
 
Create a New Folder as ViewModels and add a class file and rename it to EmployeeViewModel.cs and place the below code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using MVCCRUDProject.Models;  
  6.   
  7. namespace MVCCRUDProject.ViewModels  
  8. {  
  9.     public class EmployeeViewModel  
  10.     {  
  11.         public IEnumerable<Department> Department { getset; }  
  12.         public Employee Employee { getset; }  
  13.     }  
  14. }  
Now build & run the application. 
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
 
CRUD Using ASP.NET MVC 5 And Entity Framework
CRUD Using ASP.NET MVC 5 And Entity Framework

Conclusion

 
In this article we have learned the basic CRUD Operations using ASP.NET MVC 5 and Entity Framework.