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.
To create a new ASP.NET Web Application, select the MVC template and click on Create.
With this, a new MVC Project will be created, as shown in the below images.
Right-click on the Models folder add three classes and rename the classes as Employee.cs 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.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MVCCRUDProject.Models
{
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[Display(Name = "Employee Name")]
public string EmployeeName { get; set; }
[Display(Name = "Designation")]
public string EmployeeDesignation { get; set; }
public Department Department { get; set; }
[Display(Name = "Address")]
public string EmployeeAddress { get; set; }
[Display(Name = "Passport")]
public string EmployeePassport { get; set; }
[Display(Name = "Phone")]
public int EmployeePhone { get; set; }
[Display(Name = "Gender")]
public string EmployeeGender { get; set; }
[Display(Name = "City")]
public string City { get; set; }
[Display(Name="Project")]
public string Project { get; set; }
[Display(Name="Company Name")]
public string CompanyName { get; set; }
[Display(Name = "Pin Code")]
public int PinCode { get; set; }
[Display(Name = "Dept Name")]
public int DepartmentId { get; set; }
}
}
Open the Department. cs and paste the following code.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MVCCRUDProject.Models
{
public class Department
{
[Key]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}
}
Similarly, Open the EmployeeDbContext.cs and paste the below code.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.AccessControl;
using System.Threading;
using System.Web;
namespace MVCCRUDProject.Models
{
public class EmployeeDbContext : DbContext
{
public EmployeeDbContext()
{
}
public DbSet<Employee> Employee { get; set; }
public DbSet<Department> Department { get; set; }
}
}
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.
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 the 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 the Employee and Department tables with the Primary key and Foreign key.
namespace MVCCRUDProject.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class EmployeeDepartmentModels : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Departments",
c => new
{
DepartmentId = c.Int(nullable: false, identity: true),
DepartmentName = c.String(),
})
.PrimaryKey(t => t.DepartmentId);
CreateTable(
"dbo.Employees",
c => new
{
EmployeeId = c.Int(nullable: false, identity: true),
EmployeeName = c.String(),
EmployeeDesignation = c.String(),
EmployeeAddress = c.String(),
EmployeePassport = c.String(),
EmployeePhone = c.Int(nullable: false),
EmployeeGender = c.String(),
City = c.String(),
Project = c.String(),
CompanyName = c.String(),
PinCode = c.Int(nullable: false),
DepartmentId = c.Int(nullable: false),
})
.PrimaryKey(t => t.EmployeeId)
.ForeignKey("dbo.Departments", t => t.DepartmentId, cascadeDelete: true)
.Index(t => t.DepartmentId);
}
public override void Down()
{
DropForeignKey("dbo.Employees", "DepartmentId", "dbo.Departments");
DropIndex("dbo.Employees", new[] { "DepartmentId" });
DropTable("dbo.Employees");
DropTable("dbo.Departments");
}
}
}
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.
In order to Insert the data into these tables run the below command.
PM> Add-Migration 'UpdateDepartmentData'
With the above Command, the UpdateDepartmentData class will be created with Up() and Down() methods.
In the Up() method of UpdateDepartmentData update the code as shown below.
namespace MVCCRUDProject.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class UpdateDepartmentData : DbMigration
{
public override void Up()
{
Sql("Insert into Departments(DepartmentName)Values('IT')");
Sql("Insert into Departments(DepartmentName)Values('HR')");
Sql("Insert into Departments(DepartmentName)Values('Payroll')");
Sql("Insert into Departments(DepartmentName)Values('Talent Acquisition')");
Sql("Insert into Departments(DepartmentName)Values('Training & Development')");
}
public override void Down()
{
}
}
}
PM> Update-Database
With the execution of the above command, the above Sql Statements or records will be inserted into the Department Table.
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.
namespace MVCCRUDProject.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class UpdateEmployeeData : DbMigration
{
public override void Up()
{
Sql("Insert into Employees(EmployeeName,EmployeeDesignation,EmployeeAddress,EmployeePassport,EmployeePhone,EmployeeGender,City,Project,CompanyName,PinCode,DepartmentId)" +
"Values('KM','S.E','Hyderabad','K849271',123456789,'Male','Hyderabad','Automation','Infosys',500045,1)");
}
public override void Down()
{
}
}
}
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 the Controllers folder click on Add Controller 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.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCCRUDProject.Models;
using MVCCRUDProject.ViewModels;
namespace MVCCRUDProject.Controllers
{
public class EmployeeController : Controller
{
private readonly EmployeeDbContext _dbContext;
public EmployeeController()
{
this._dbContext = new EmployeeDbContext();
}
// GET: Employee
public ActionResult Index()
{
var employeeList = this._dbContext.Employee.Include(x => x.Department).ToList();
return View(employeeList);
}
public ActionResult AddEmployees()
{
var employeeViewModel = new EmployeeViewModel()
{
Department = this._dbContext.Department.ToList(),
Employee = new Employee()
};
return View("EmployeeForm", employeeViewModel);
}
public ActionResult Edit(int id)
{
var employees = this._dbContext.Employee.FirstOrDefault(x => x.EmployeeId == id);
var department = this._dbContext.Department.ToList();
var viewModel = new EmployeeViewModel()
{
Department = department,
Employee = employees
};
return View("EmployeeForm", viewModel);
}
[HttpPost]
public ActionResult Save(Employee employee)
{
if (!ModelState.IsValid)
{
return RedirectToAction("AddEmployees", "Employee");
}
if (employee.EmployeeId == 0)
this._dbContext.Employee.Add(employee);
else
{
var employeesDb = this._dbContext.Employee.FirstOrDefault(x => x.EmployeeId == employee.EmployeeId);
employeesDb.EmployeeName = employee.EmployeeName;
employeesDb.EmployeeDesignation = employee.EmployeeDesignation;
employeesDb.EmployeeAddress = employee.EmployeeAddress;
employeesDb.EmployeePassport = employee.EmployeePassport;
employeesDb.EmployeePhone = employee.EmployeePhone;
employeesDb.EmployeeGender = employee.EmployeeGender;
employeesDb.City = employee.City;
employeesDb.Project = employee.Project;
employeesDb.CompanyName = employee.CompanyName;
employeesDb.PinCode = employee.PinCode;
employeesDb.DepartmentId = employee.DepartmentId;
}
this._dbContext.SaveChanges();
return RedirectToAction("Index", "Employee");
}
public ActionResult Delete(int id)
{
var employeeDb = this._dbContext.Employee.FirstOrDefault(x => x.EmployeeId == id);
this._dbContext.Employee.Remove(employeeDb);
this._dbContext.SaveChanges();
return RedirectToAction("Index", "Employee");
}
}
}
In the Views Folder, add a new folder as Employee and add two Views or .cshtml files as EmployeeForm.cshtml and Index. cshtml under the Employee folder.
Open Index. cshtml add place the below code.
@model IEnumerable<MVCCRUDProject.Models.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Employee Details</h2>
<hr/>
<button class="">@Html.ActionLink("Add Employees", "AddEmployees", "Employee")</button>
<table class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(m => m.EmployeeName)</th>
<th>@Html.DisplayNameFor(m => m.EmployeeDesignation)</th>
<th>@Html.DisplayNameFor(m => m.EmployeeAddress)</th>
<th>@Html.DisplayNameFor(m => m.EmployeePassport)</th>
<th>@Html.DisplayNameFor(m => m.EmployeePhone)</th>
<th>@Html.DisplayNameFor(m => m.EmployeeGender)</th>
<th>@Html.DisplayNameFor(m => m.City)</th>
<th>@Html.DisplayNameFor(m => m.Project)</th>
<th>@Html.DisplayNameFor(m => m.CompanyName)</th>
<th>@Html.DisplayNameFor(m => m.PinCode)</th>
<th>@Html.DisplayNameFor(m => m.DepartmentId)</th>
</tr>
</thead>
<tbody>
@foreach (var employees in Model)
{
<tr>
<td>@employees.EmployeeName</td>
<td>@employees.EmployeeDesignation</td>
<td>@employees.EmployeeAddress</td>
<td>@employees.EmployeePassport</td>
<td>@employees.EmployeePhone</td>
<td>@employees.EmployeeGender</td>
<td>@employees.City</td>
<td>@employees.Project</td>
<td>@employees.CompanyName</td>
<td>@employees.PinCode</td>
<td>@employees.Department.DepartmentName</td>
<td>@Html.ActionLink("Edit", "Edit", new { id = employees.EmployeeId })</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = employees.EmployeeId })</td>
</tr>
}
</tbody>
</table>
Similarly, open the EmployeeForm.cshtml and place the below code.
@model MVCCRUDProject.ViewModels.EmployeeViewModel
@{
ViewBag.Title = "EmployeeForm";
}
<h2>Employee Details</h2>
<hr />
@using (@Html.BeginForm("Save", "Employee"))
{
<div class="form-group">
@Html.LabelFor(m => m.Employee.EmployeeName)
@Html.TextBoxFor(m => m.Employee.EmployeeName, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.EmployeeDesignation)
@Html.TextBoxFor(m => m.Employee.EmployeeDesignation, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.EmployeeAddress)
@Html.TextBoxFor(m => m.Employee.EmployeeAddress, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.EmployeePassport)
@Html.TextBoxFor(m => m.Employee.EmployeePassport, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.EmployeePhone)
@Html.TextBoxFor(m => m.Employee.EmployeePhone, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.EmployeeGender)
@Html.TextBoxFor(m => m.Employee.EmployeeGender, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.City)
@Html.TextBoxFor(m => m.Employee.City, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.Project)
@Html.TextBoxFor(m => m.Employee.Project, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.CompanyName)
@Html.TextBoxFor(m => m.Employee.CompanyName, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.PinCode)
@Html.TextBoxFor(m => m.Employee.PinCode, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Employee.DepartmentId)
@Html.DropDownListFor(m => m.Employee.DepartmentId, new SelectList(Model.Department, "DepartmentId", "DepartmentName"), "Select Department", new { @class = "form-control" })
</div>
@Html.HiddenFor(m => m.Employee.EmployeeId)
var c = @Model.Employee.EmployeeId > 0 ? "Update" : "Save";
<button type="submit" class="btn btn-primary">@c</button>
}
Here in the above code for declaration, we used ViewModel as we are using Employee and Department properties.
Create a New Folder as ViewModels add a class file rename it to EmployeeViewModel.cs and place the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCCRUDProject.Models;
namespace MVCCRUDProject.ViewModels
{
public class EmployeeViewModel
{
public IEnumerable<Department> Department { get; set; }
public Employee Employee { get; set; }
}
}
Now build & run the application.
Conclusion
In this article, we have learned the basic CRUD Operations using ASP.NET MVC 5 and Entity Framework.