Loading

ASP.NET MVC

How to perform CRUD Operations using Entity Framework?. The Complete ASP.NET MVC Developer Course 2022 [Videos].

In this and in few upcoming Videos, I am going to discuss how to perform CRUD operations using Entity Framework in ASP.NET MVC application. Please watch our previous Video where we discussed how to Delete Database Records in ASP.NET MVC Application with some examples.

Database Tables used in this Demo:

In this demo, we are going to use the following Department and Employee table. So, please use the below SQL script to create and populate these 2 tables

Create table Department
(
Id int primary key identity,
Name nvarchar(50)
)



Create table Employee
(
EmployeeId int Primary Key Identity(1,1),
Name nvarchar(50),
Gender nvarchar(10),
City nvarchar(50),
Salary decimal(18,2),
DepartmentId int
)
Alter table Employee add foreign key (DepartmentId) references Department(Id)
Open File => New =>Project and then select Installed => Templates => Visual C#. Then select ASP.NET Web Application. Provide the project name and location where you want to save your application and finally click on the OK button as shown in the below image.

CRUD Operations using Entity Framework in ASP.NET MVC

From the next screen that is from select a template screen, select Empty as the project template. From add folder and core reference section check the MVC checkbox and click on OK as shown below.

Selecting Project Template in ASP.NET MVC Application

Once you click on the OK button, it will take some time to create the project for us.

Adding ADO.NET Entity Data Model

Right-click on Models folder then select Add => New Item from the context menu that will open the Add New Item window. Select the Data tab from the left panel and then choose ADO.NET Entity Data Model from the middle panel. Provide a meaningful name for your data model and click on the Add button as shown in the below image.

Adding ADO.NET Entity Data Model in ASP.NET MVC Application

Selecting The Entity Framework Approach to interact with the database.

Once you click on the Add button it will ask you to choose the entity framework approach. Here, we are going to use the database first approach as we alwatchy created the required database tables. So, from the Entity Data Model Wizard, select “Generate from database” option and click “Next” as shown below.

Selecting Database First Approach in Entity Framework

Creating Database Connection:

On “Choose your data connection screen” and click on the “New Connection” button which will open the connection properties window. Here, we are going to interact with the SQL Server database. So, from the Data Source select Microsoft SQL Server (SqlClient). Provide your SQL Server name. Choose the Authentication type. Here, I am choosing Windows Authentication. Then select the database to which you are going to interact from the select or enter a database name drop-down list. Finally, click on the “OK” as shown below.

Creating Database Connection in Entity Framework Database First Approach

Then provide a meaningful connection string name such as “EmployeeDBContext” and click on the “Next” button as shown below.

CRUD Operations using Entity Framework in ASP.NET MVC

Choose Entity Framework Version:

Here, we are going to use Entity Framework 6. So, from the Choose Your Version screen, choose the Entity framework 6.x  and click on the Next button as shown below.

Selecting Entity Framework Version in ASP.NET MVC Application

Selecting Database Objects and Settings:

On “Choose your database objects and Settings” screen, expand the “Tables” and then select “Department” and “Employee” tables. Set Model Namespace as Models and click on the “Finish” button as shown in the below image.

Selecting Database Objects and Settings in Entity Framework

At this point, we should have Department and Employee entities generated as shown below.

CRUD Operations using Entity Framework in ASP.NET MVC Application

Creating MVC 5 Controller:

Right-click on the “Controllers” folder and select Add – Controller from the context menu. Then select MVC 5 Controller with views, using Entity Framework and click on the Add button as shown in the below image.

Creating MVC 5 Controller using Entity Framework

On the next screen set the below details

  1. Model class = Employee (CRUD_Using_EF.Models)
  2. Data Context Class = EmployeeDBContext(CRUD_Using_EF.Models)
  3. Controller Name = EmployeeController
  4. Rest values are as it is and click on the Add button as shown in the below image

Setting Controller Properties to Create Views and Action Methods

At this point, we should have the following files automatically added.

EmployeeController.cs file in “Controllers” folder. Index, Create, Edit, Detail and Delete views in the “Employee” folder which is inside the Views folder.

Below is the EmployeeController code
namespace CRUD_Using_EF.Controllers
{
public class EmployeeController : Controller
{
private EmployeeDBContext db = new EmployeeDBContext();
// GET: Employee
public ActionResult Index()
{
var employees = db.Employees.Include(e => e.Department);
return View(employees.ToList());
}
// GET: Employee/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return HttpNotFound();
}
return View(employee);
}
// GET: Employee/Create
public ActionResult Create()
{
ViewBag.DepartmentId = new SelectList(db.Departments, "Id", "Name");
return View();
}
// POST: Employee/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EmployeeId,Name,Gender,City,Salary,DepartmentId")] Employee employee)
{
if (ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList(db.Departments, "Id", "Name", employee.DepartmentId);
return View(employee);
}
// GET: Employee/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return HttpNotFound();
}
ViewBag.DepartmentId = new SelectList(db.Departments, "Id", "Name", employee.DepartmentId);
return View(employee);
}
// POST: Employee/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "EmployeeId,Name,Gender,City,Salary,DepartmentId")] Employee employee)
{
if (ModelState.IsValid)
{
db.Entry(employee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList(db.Departments, "Id", "Name", employee.DepartmentId);
return View(employee);
}
// GET: Employee/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.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.Employees.Find(id);
db.Employees.Remove(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}

At this point if you run the application you will get an error stating – The resource cannot be found. This is because by default the application goes to the “Home” controller and “Index” action. To fix this, open “RouteConfig.cs” file from the “App_Start” folder and set the controller as “Employee” as shown below.

RouteConfig File in ASP.NET MVC Application

Run the application again. Notice that all the employees are listed on the index view. We can also create a new employee, edit an employee, view their full details and delete an employee as well. However, there are a few issues with each of the views which we will address in our upcoming Videos.

See All

Comments (288 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /288

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /288

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /288