CRUD Operations using Repository Pattern in Asp.Net MVC with Example

  Total Views : 3218
  Comments : 4
 
  Keywords : Asp.net mvc crud operations with repository pattern using entity framework, Learn repository pattern in asp.net mvc with crud operations example, Generic repository pattern in asp.net mvc

Here we will learn repository pattern in asp.net mvc, use of repository pattern and how to implement crud operations using repository pattern in asp.net mvc with entity framework example.

Repository Pattern in Asp.Net MVC

The generic repository pattern in asp.net mvc is a data access pattern it is used make your application loosely coupled. Generic repository pattern in asp.net mvc is a kind of layer which work between business layer and data access layer. Instead of writing entire data access logic on controller it’s better to write this logic in different class called as repository. This will make your code more maintainable and understandable.

Create New Application in Asp.Net MVC

Now let's understand repository pattern with simple crud operations example in asp.net. For that Open visual studio studio à Go to File à Select New à Select Project 

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “MVCrepo” then finally click on ok button. Our project structure will be like as shown below 

 

Data Repository Application in asp.net mvc

 

After creating solution now let’s create a folder with name “repository” to store repository related classes and interface.

 

Adding repository folder in asp.net mvc application

After creating repository folder now we need to Install Entity framework in our application

Installing Entity framework in Asp.Net Application

For adding Entity framework just right click on your application and from above list select “Manage NuGet Packages”.

 

installing manage nuget package in asp.net mvc application

 

After select a new dialog will popup for “Manage NuGet Packages” inside search box enter “Entityframework”. After getting search value select Entityframework click on install button 

 

Installing Entity Framework in Asp.net mvc application

 

After adding it will show an ok sign in green color

 

After installed entity framework it will shows green color in asp.net mvc application

 

After installing Entity framework now we are going to add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

For adding ADO.NET Entity Data Model just right click on Model folder and select Add inside that Select ADO.NET Entity Data Model to our solution

 

Asp.net mvc add ado.net entity data model in repository pattern application

 

After that a small dialog will pop up for asking ADO.NET Entity Data Model Name I will name it as EmployeeDB

 

select employeedb model in ado.net entity framework in asp.net mvc application

 

After that a new Wizard will popup where we are going configure Entity Data Model. In this we are going to use Database first

 

Entity Data Model Wizard with Database conneciton in asp.net mvc application

 

From that select Generate from database and click on Next button. After clicking on Next button a New Wizard will pop up for Choosing Data Connection.

Choosing Data Connection

Asp.Net MVC Choose New Database Connection in Entity Data Model

 

Now click on New Connection a new Dialog will popup. Here we need to configure it. In Server name you need to add your Sql Server Name and select either Using Windows Authentication or Using Sql Server Authentication to connect SQL Server. Here we selected Using Sql Server Authentication and entered User name and Password of Sql server. Last we are going to select Database Name- EmployeeDB once we done click on OK button as shown below

 

configure database connection in repository pattern in asp.net mvc application

 

After adding database connection our Entity Data Model Wizard will look like below snapshot

 

configure database connection in repository pattern in asp.net mvc application

 

Now click on Next button. A new wizard will pop up for selecting database object and in this you will see all the table which we have created in database

 

select database table from database in generic repository pattern in asp.net mvc

 

Finally click on Finish button. After adding ADO.NET Entity Data Model our application will be like as shown below

 

After adding ado.net connection in asp.net mvc application

 

 After creating ADO.NET Entity Data Model we first need to add interface in repository folder and going to name interface with name “IEmployee”. 

 

For adding Interface Right click on repository folder à select Add à then select Class and name it as IEmployee. Once we add our project structure like as shown below 

 

Adding interface file to repository folder in asp.net mvc

 

Now open IEmployee class file in that remove class word from file and type Interface like as shown below 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace MVCrepo.repository

{

interface IEmployee

{

 

}

}

Now inside this Interface we are going declare our CRUD methods that will be like as shown below 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using MVCrepo.Models;

 

namespace MVCrepo.repository

{

interface IEmployee

{

void InsertEmployee(EmployeeDetail Employee); // C

IEnumerable<EmployeeDetail> GetEmployees(); // R

EmployeeDetail GetEmployeeByID(int EmployeeId); // R

void UpdateEmployee(EmployeeDetail Employee); //U

void DeleteEmployee(int EmployeeId); //D

void Save();

}

}

After adding interface and CRUD methods now we are going add a class in repository folder with name “EmployeeRepository” that will implement IEmployee interface. For that right click on repository folder à Select Add à then select Class like as shown below

 

add class file to repository folder in asp.net mvc application 

After clicking on Class a new dialog will pop up for asking Class Name in that mention name of class file as "EmployeeRepository" like as shown below 

 

give to respository class file in repository pattern in asp.net mvc

 

 After adding EmployeeRepository file our project structure will be like as shown below 

 

Project structure after adding respository class file in asp.net mvc applicaiton

 

Now open EmployeeRepository file and write the code like as shown below 

 

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Web;

using MVCrepo.Models;

 

namespace MVCrepo.repository

{

public class EmployeeRepository : IEmployee

{

private EmployeeDBEntities DBcontext;

public EmployeeRepository(EmployeeDBEntities objempcontext)

{

this.DBcontext = objempcontext;

}

public void InsertEmployee(Models.EmployeeDetail Employee)

{

DBcontext.EmployeeDetails.Add(Employee);

DBcontext.SaveChanges();

}

public IEnumerable<Models.EmployeeDetail> GetEmployees()

{

return DBcontext.EmployeeDetails.ToList();

}

public Models.EmployeeDetail GetEmployeeByID(int EmployeeId)

{

return DBcontext.EmployeeDetails.Find(EmployeeId);

}

public void UpdateEmployee(Models.EmployeeDetail Employee)

{

DBcontext.Entry(Employee).State = EntityState.Modified;

DBcontext.SaveChanges();

}

public void DeleteEmployee(int EmployeeId)

{

EmployeeDetail user = DBcontext.EmployeeDetails.Find(EmployeeId);

DBcontext.EmployeeDetails.Remove(user);

DBcontext.SaveChanges();

}

}

}

After implement Interface now let’s add a Controller and Action method for calling this method and making them work. For adding controller just Right click on Controller Folder à inside that select Add à then select Controller. 

 

After selecting Controller a new dialog will pop up for asking Controller name and other configuration details. Name Controller as “EmpController” and while adding and in Template select “Mvc controller with empty read/write actions” this will create a whole structure of CRUD method for you. 

 

MVC Controller with empty read/write actions in asp.net mvc application

 

After adding controller below is the complete code which will be generated by scaffolding template.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MVCrepo.Controllers

{

public class EmpController : Controller

{

//

// GET: /Emp/

public ActionResult Index()

{

return View();

}

//

// GET: /Emp/Details/5

public ActionResult Details(int id)

{

return View();

}

//

// GET: /Emp/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Emp/Create

[HttpPost]

public ActionResult Create(FormCollection collection)

{

try

{

// TODO: Add insert logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

//

// GET: /Emp/Edit/5

public ActionResult Edit(int id)

{

return View();

}

//

// POST: /Emp/Edit/5

[HttpPost]

public ActionResult Edit(int id, FormCollection collection)

{

try

{

// TODO: Add update logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

//

// GET: /Emp/Delete/5

public ActionResult Delete(int id)

{

return View();

}

//

// POST: /Emp/Delete/5

[HttpPost]

public ActionResult Delete(int id, FormCollection collection)

{

try

{

// TODO: Add delete logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

}

}

Now let’s add some code in Action Method. First thing we will create a constructor in EmpController class where we will call EmployeeRepository class and pass EmployeeDBEntities to it.

 

public class EmpController : Controller

{

private IEmployee Iemp;

public EmpController()

{

this.Iemp = new EmployeeRepository(new EmployeeDBEntities());

}

}

Now after adding a constructer we are moving to first Action Method Index in this method whenever user call or access this page we are going to show him list of all records. For that we are going to return an IEnumerable list.

 

public ActionResult Index()

{

var list = Iemp.GetEmployees().ToList();

return View(list);

}

After adding return List to view in Index now going to create a view which will take List as input and display records in Gridview way.

 

For Adding View just right click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form.

 

Here in below snapshot we selected View engine as Razor and we are going to create a strongly type view for that we selected Model class EmployeeDetail and we want to generate a list for that I have selected List in Scaffold template finally click on Add button. 

 

add view to controller in asp.net mvc application

 

After adding view here below is a complete View of Index.cshtml which is generated. In our view Index.cshtml we need to write the code like as shown below 

 

@model IEnumerable<MVCrepo.Models.EmployeeDetail>

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Details</title>

</head>

<body>

<p>

@Html.ActionLink("Create New", "Create")

</p>

<table>

<tr>

<th>

@Html.DisplayNameFor(model => model.Name)

</th>

<th>

@Html.DisplayNameFor(model => model.Address)

</th>

<th>

@Html.DisplayNameFor(model => model.Age)

</th>

<th>

@Html.DisplayNameFor(model => model.Salary)

</th>

<th>

@Html.DisplayNameFor(model => model.worktype)

</th>

<th></th>

</tr>

 

@foreach (var item in Model) {

<tr>

<td>

@Html.DisplayFor(modelItem => item.Name)

</td>

<td>

@Html.DisplayFor(modelItem => item.Address)

</td>

<td>

@Html.DisplayFor(modelItem => item.Age)

</td>

<td>

@Html.DisplayFor(modelItem => item.Salary)

</td>

<td>

@Html.DisplayFor(modelItem => item.worktype)

</td>

<td>

@Html.ActionLink("Edit", "Edit", new { id=item.EmpID }) |

@Html.ActionLink("Details", "Details", new { id=item.EmpID }) |

@Html.ActionLink("Delete", "Delete", new { id=item.EmpID })

</td>

</tr>

}

</table>

</body>

</html>

Output of Index.cshtml View like as shown below

 

Showing User details in asp.net mvc application

Show Employee Details (By ID)

After completing display List now we are going to show Record Details whenever we click on Details link from above grid which well take EmpID and Call Details Action result. From that ID we are going to get record and display. Link for calling Details Action Method

 

@Html.ActionLink("Details", "Details", new { id=item.EmpID })

Our Details action method will be like as shown below 

 

public ActionResult Details(int id)

{

var objemp = Iemp.GetEmployeeByID(id);

var Employee = new EmployeeDetail();

Employee.EmpID = id;

Employee.Name = objemp.Name;

Employee.Salary = objemp.Salary;

Employee.Age = objemp.Age;

Employee.Address = objemp.Address;

Employee.worktype = objemp.worktype;

return View(Employee);

}

After taking id as input it will return an Employee model to Details view and Details view will take this Model as input and generate view. Here is below code of Details.cshtml

 

@model MVCrepo.Models.EmployeeDetail

@{

Layout = null;

}

 

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Index</title>

</head>

<body>

<fieldset>

<legend>EmployeeDetail</legend>

<div class="display-label">

@Html.DisplayNameFor(model => model.Name)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Name)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.Address)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Address)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.Age)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Age)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.Salary)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Salary)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.worktype)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.worktype)

</div>

</fieldset>

<p>

@Html.ActionLink("Edit", "Edit", new { id=Model.EmpID }) |

@Html.ActionLink("Back to List", "Index")

</p>

</body>

</html>

Output of Details.cshtml View like as shown below 

 Show Employee Details in Asp.net repository pattern

Create New Employee

After showing employee Details View now we will create a Create View which take user input and post server. In this we are going to have 2 Action selectors method.

 

  1. HttpGet
  2. HttpPost

[HttpGet] - Represents an attribute that is used to restrict an action method so that the method handles only HTTP GET requests.

 

[HttpPost] - Represents an attribute that is used to restrict an action method so that the method handles only HTTP POST requests.

HttpGet of Create 

When we are going to call Create Action Method then HttpGet will get fired and this will return a blank Employee Model for creating a Create View.

 

[HttpGet]

public ActionResult Create()

{

return View(new EmployeeDetail());

}

 Here is below code of Create.cshtml

 

@model MVCrepo.Models.EmployeeDetail

 

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

 

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

<legend>EmployeeDetail</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.Age)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.Age)

@Html.ValidationMessageFor(model => model.Age)

</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>

<div class="editor-label">

@Html.LabelFor(model => model.worktype)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.worktype)

@Html.ValidationMessageFor(model => model.worktype)

</div>

<p>

<input type="submit" value="Create"/>

</p>

</fieldset>

}

<div>

@Html.ActionLink("Back to List", "Index")

</div>

Output of Create.cshtml View

Create employee details in asp.net mvc application

 

We finished HttpGet part now let's move to HttpPost method.

HttpPost of Create

When we are going to click on Create button of Create.cshtml View then it will post this Form to server in this we are using tight coupling Employee model that carry data to server and HttpPost Method of Create will take Employee Model as Input and pass data to InsertEmployee Method of EmployeeRepository for saving data. Here is code snippet of Create HttpPost Method.

 

[HttpPost]

public ActionResult Create(FormCollection collection, EmployeeDetail objemp)

{

try

{

var Employee = new EmployeeDetail();

Employee.EmpID = 0;

Employee.Name = objemp.Name;

Employee.Salary = objemp.Salary;

Employee.Age = objemp.Age;

Employee.Address = objemp.Address;

Employee.worktype = objemp.worktype;

Iemp.InsertEmployee(Employee); // Passing data to InsertEmployee of EmployeeRepository

return RedirectToAction("Index");

}

catch

{

return View();

}

}

Edit Employee Details

After completing with create now we are moving towards Edit page it is little bit similar Create and List .In this we are going to Take Id as input and according to id we are going to retrieve data from database using EmployeeRepository.

 

HttpGet of Edit

In this we are going to have 2 Action selectors method.

 

  1. HttpGet
  2. HttpPost

The first HttpGet method will take ID and Get records and Return it to view. From Grid we are going to select Edit link which will take EmpID and Call Edit Action thod

 

Showing Employee Details in asp.net mvc application

Link for calling Edit Action Method

 

  @Html.ActionLink("Edit", "Edit", new { id=item.EmpID })

Here below is code snippet of Edit HttpGet Method

 

public ActionResult Edit(int id)

{

var objemp = Iemp.GetEmployeeByID(id); // getting records by id GetEmployeeByID(ID)

var Employee = new EmployeeDetail();

Employee.EmpID = id;

Employee.Name = objemp.Name;

Employee.Salary = objemp.Salary;

Employee.Age = objemp.Age;

Employee.Address = objemp.Address;

Employee.worktype = objemp.worktype;

return View(Employee);

}

This edit method will return Employee model which will be input to Edit View and it will display records according to it. Here is below code of Edit.cshtml

 

@model MVCrepo.Models.EmployeeDetail

@{ Layout = null; }

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Edit</title>

</head>

<body>

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

 

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

 

<fieldset>

<legend>EmployeeDetail</legend>

@Html.HiddenFor(model => model.EmpID)

<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.Age)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.Age)

@Html.ValidationMessageFor(model => model.Age)

</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>

<div class="editor-label">

@Html.LabelFor(model => model.worktype)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.worktype)

@Html.ValidationMessageFor(model => model.worktype)

</div>

<p>  <input type="submit" value="Save"/> </p>

</fieldset>

}

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

</body>

</html>

Output of Edit.cshtml View

Edit Employee Details in asp.net mvc application

HttpPost of Edit

When we are going to click on save button of Edit.cshtml View then it will post this Form to server in this we are using tight coupling Employee model that carry data to server and HttpPost Method of Edit will take Employee Model as Input and pass data to UpdateEmployee Method of EmployeeRepository for Updating data.

 

After Updating it will redirect to Index. Here below is code snippet of Edit HttpPost Method

 

[HttpPost]

public ActionResult Edit(FormCollection collection, EmployeeDetail objemp)

{

try

{

var Employee = new EmployeeDetail();

Iemp.UpdateEmployee(objemp); // calling UpdateEmployee method of EmployeeRepository

return RedirectToAction("Index");

}

catch

{

return View();

}

}

Delete Employee Details

After Completing Edit now we are finally at last moving towards Delete method. In this we are going to have 2 Action selectors method.

 

  1. HttpGet
  2. HttpPost

The first HttpGet method will take ID and Get records and Return it to view. From Grid we are going to select Delete link which will take EmpID and Call Delete Action Method.

 

asp.net mvc Insert details using repository pattern with entity framework

Link for calling Delete Action Method

 

@Html.ActionLink("Delete", "Delete", new { id=item.EmpID })

Here below is code snippet of Delete HttpGet Method

 

public ActionResult Delete(int id)

{

var objemp = Iemp.GetEmployeeByID(id); // calling GetEmployeeByID method of EmployeeRepository

return View(objemp);

}

This Delete method will take EmpID as input and return Employee model which will be input to Delete View and it will display records according to it. Here is below code of Delete.cshtml

 

@model MVCrepo.Models.EmployeeDetail

 

@{

Layout = null;

}

 

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Delete</title>

</head>

<body>

<h3>Are you sure you want to delete this?</h3>

<fieldset>

<legend>EmployeeDetail</legend>

<div class="display-label">

@Html.DisplayNameFor(model => model.Name)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Name)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.Address)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Address)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.Age)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Age)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.Salary)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Salary)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.worktype)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.worktype)

</div>

</fieldset>

@using (Html.BeginForm()) {

<p>

<input type="submit" value="Delete"/> |

@Html.ActionLink("Back to List", "Index")

</p>

}

</body>

</html>

Output of Delete.cshtml View

 

Delete employee details in asp.net mvc application

HttpPost of Delete

When we are going to click on Delete button of Delete.cshtml View then it will post this Form to server in this we are using tight coupling Employee model that carry data to server and HttpPost Method of Delete will take Employee Model as Input and pass data to DeleteEmployee Method of EmployeeRepository for Deleting data. After Deleting it will redirect to Index.

 

[HttpPost]

public ActionResult Delete(int id, EmployeeDetail objemp)

{

try

{

Iemp.DeleteEmployee(id); // calling DeleteEmployee method of EmployeeRepository

return RedirectToAction("Index");

}

catch

{

return View();

}

}

Finally we completed generic repository pattern in asp.net mvc in step by step manner with crud operations.

 Comments (4)

  • Anjani Pandey tutlane registered profile image
     
    Anjani Pandey   Reply

    Sai Good One.

     Feb 23, 2016
  • Anjani Pandey tutlane registered profile image
     
    Anjani Pandey   Reply

    Post about Bundling and Minfi.. in MVC

     Feb 23, 2016
    • Suresh Dasari tutlane registered profile image
       
      Suresh Dasari

      check this article for bundling and minification in asp.net http://tutlane.com/tutorial/aspnet-mvc/asp-net-mvc-bundling-and-minification

       Jul 19, 2016
  • tushar chorghe tutlane registered profile image
     
    tushar chorghe   Reply

    very nice !!

     Aug 23, 2016

Leave a comment

  • Default Tutlane User