Hello Friends, In this tutorial, I am going to show you how to perform CRUD operation using Entity Framework in ASP.NET MVC. We have already discussed Entity Framework in our previous session. Let’s Start the session.

Introduction:

Here I will create a simple example to perform CRUD operation using Entity Framework in ASP.NET MVC without writing a single line of code. Entity Framework is ORM framework that eliminates the need of accessive line of code for any database operation.

CRUD

 

CRUD Operation using Entity Framework in ASP.NET MVC:

Create Database:

Open SQL Server and Create a database called EntityDemo.

CREATE DATABASE EntityDemo

Create an Employee table. Here is the script.

USE [EntityDemo]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Employee](
 [EmployeeID] [varchar](100) NOT NULL,
 [Name] [varchar](150) NULL,
 [Address] [varchar](100) NULL,
 [Salary] [float] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
 [EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Insert few records into Employee table.

INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E001','Manish Kumar','New Delhi',10000)
INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E002','Abhishek Kumar','Chennai',20000)
INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E003','Nitesh Singh','Noida',25000)
INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E004','Vikas Singh','Pune',300000)

Run the following query to verify the table data.

SELECT * FROM [dbo].[Employee]

CRUD

All done with databse part. Now it’s time to work with the application part.

Open Visual Studio and create an MVC4 application:

CRUD

Choose an empty template and create OK. An empty solution will be created.

CRUD

If you will not choose an empty solution and you will get a default empty solution with HomeController.in the Controller Folder. By default Entity Framework is downloaded as a package in the application folder. If your application does not contain Entity Framework package you can download the Entity Framework package by just following the steps:

Goto Tools>Library Package Manager>Package Manager Console and install Entity Framework packages using the following Command.

CRUD

Install-Package EntityFramework -Version 5.0.0

CRUD

 

Add ADO.NET Entity Model to the Project:

Right Click on the Solution Explorer and select Add New Item to add ADO.NET Entity Model.

CRUD

Enter EmployeeModel in name Textbox and Click on the Add button.

CRUD

The next screen that will appear should look like this. Choose Generate From Database and click on the Next button.

CRUD

Click on the New Connection button. The Next screen that will appear will look like this. Enter the values that are circled in the below snapshot and click on the OK button.

CRUD

 

CRUD

The next Screen Will look like this. Click on the Next button.

 

CRUD

Check the  Tables checkbox and click on the Finish button as in above snapshot.

CRUD

Now we have done with the ADO.NET Entity Model part. The output window should look like this.

CRUD

Right Click on the Controller folder and Create a Controller called EmployeeController

CRUD

Type the name HomeCotroller in the Controller Name textbox. Select MVC controller with read/write actions and views, using Entity Framework From the Scaffolding Options,  Select Employee. Select Employee Data Context class and click on the Add button as in below snapshot.

CRUD

HomeController with the following code will be created.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EntityCRUDDemo.Controllers
{
 public class HomeController : Controller
 {
 private EntityDemoEntities db = new EntityDemoEntities();

//
 // GET: /Home/

public ActionResult Index()
 {
 return View(db.Employees.ToList());
 }

//
 // GET: /Home/Details/5

public ActionResult Details(string id = null)
 {
 Employee employee = db.Employees.Find(id);
 if (employee == null)
 {
 return HttpNotFound();
 }
 return View(employee);
 }

//
 // GET: /Home/Create

public ActionResult Create()
 {
 return View();
 }

//
 // POST: /Home/Create

[HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Create(Employee employee)
 {
 if (ModelState.IsValid)
 {
 db.Employees.Add(employee);
 db.SaveChanges();
 return RedirectToAction("Index");
 }

return View(employee);
 }

//
 // GET: /Home/Edit/5

public ActionResult Edit(string id = null)
 {
 Employee employee = db.Employees.Find(id);
 if (employee == null)
 {
 return HttpNotFound();
 }
 return View(employee);
 }

//
 // POST: /Home/Edit/5

[HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Edit(Employee employee)
 {
 if (ModelState.IsValid)
 {
 db.Entry(employee).State = EntityState.Modified;
 db.SaveChanges();
 return RedirectToAction("Index");
 }
 return View(employee);
 }

//
 // GET: /Home/Delete/5

public ActionResult Delete(string id = null)
 {
 Employee employee = db.Employees.Find(id);
 if (employee == null)
 {
 return HttpNotFound();
 }
 return View(employee);
 }

//
 // POST: /Home/Delete/5

[HttpPost, ActionName("Delete")]
 [ValidateAntiForgeryToken]
 public ActionResult DeleteConfirmed(string id)
 {
 Employee employee = db.Employees.Find(id);
 db.Employees.Remove(employee);
 db.SaveChanges();
 return RedirectToAction("Index");
 }

protected override void Dispose(bool disposing)
 {
 db.Dispose();
 base.Dispose(disposing);
 }
 }
}

You can see the following Views are created automatically in the Views folder.

CRUD

If you see your View for creating Employee Record, you will not find an option for EmployeeID.

@model EntityCRUDDemo.Employee

@{
 ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true)

<fieldset>
 <legend>Employee</legend>
 
 <div class="editor-label">
 @Html.LabelFor(model => model.Name)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Name)
 @Html.ValidationMessageFor(model => model.Name)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Address)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Address)
 @Html.ValidationMessageFor(model => model.Address)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Salary)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Salary)
 @Html.ValidationMessageFor(model => model.Salary)
 </div>

<p>
 <input type="submit" value="Create" />
 </p>
 </fieldset>
}

<div>
 @Html.ActionLink("Back to List", "Index")
</div>

Replace your Create.cshtml file.

@model EntityCRUDDemo.Employee

@{
 ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true)

<fieldset>
 <legend>Employee</legend>
 <div class="editor-label">
 @Html.LabelFor(model => model.EmployeeID)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.EmployeeID)
 @Html.ValidationMessageFor(model => model.EmployeeID)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Name)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Name)
 @Html.ValidationMessageFor(model => model.Name)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Address)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Address)
 @Html.ValidationMessageFor(model => model.Address)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Salary)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Salary)
 @Html.ValidationMessageFor(model => model.Salary)
 </div>

<p>
 <input type="submit" value="Create" />
 </p>
 </fieldset>
}

<div>
 @Html.ActionLink("Back to List", "Index")
</div>

Run the application and look at the output screen.

Index View:

CRUD

Create View:

CRUD

Edit View:

CRUD

Details:

CRUD

You can download the complete source code for the application from here.

Download the Database Script from here.

Hope you understand the CRUD operation using Entity Framework in ASP.NET.

View More:

Thank You.

 

 

Leave a Comment