Introduction
This article will explain the repository design pattern in ASP.NET MVC. We will discuss CRUD (Create, Update, Read and Delete) operations using Repository Design Pattern in ASP.NET MVC. The Repository Design Pattern in C# is one of the most used design patterns in real-time applications.
Nowadays, most of the data-driven applications need to access the data residing in one or more other data sources. The easiest or simplest approach is to write all the data access related code in the main application itself.
Repository Design Pattern in C#
The Repository Design Pattern in C# works as a mediator between the domain and the data mapping layers using a collection-like interface for accessing the domain objects.
In other words, we can say that a Repository Design Pattern acts as a bridge between the rest of the application and the data access logic. That means a repository pattern isolates all the data access code from the rest of the application. The advantage of doing so is that if you need to make any change, then you have to do that only once in one place. Another benefit is that testing your controllers becomes easy because the testing framework needs not run against the actual database access code with a Repository Design Pattern introduced.
Let's see this with a demo application.
Step 1
Open SQL Server and create a database table to perform CRUD.
- CREATE TABLE [dbo].[Employee](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [FirstName] [nvarchar](50) NULL,
- [LastName] [nvarchar](50) NULL,
- [Age] [int] NULL,
- [Position] [nvarchar](50) NULL,
- [Office] [nvarchar](50) NULL,
- [Salary] [int] NULL,
- CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
- (
- [Id] 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
Step 2
Open Visual Studio 2015 or a version of your choice and create a new project.
Step 3
Choose web application project and give the appropriate name to your project.

Step 4
Select "empty template", check on MVC checkbox, and click OK.

Step 5
Right-click the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".

After clicking on Next, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".

Entity Framework gets added and the respective class gets generated under the Models folder.

Employee class
- using System.ComponentModel.DataAnnotations;
- namespace MvcRepositoryDesignPattern_Demo.Models
- {
- using System;
- using System.Collections.Generic;
- public partial class Employee
- {
- public int Id { get; set; }
- [Required(ErrorMessage = "Please enter first name")]
- [Display(Name="First Name")]
- public string FirstName { get; set; }
- [Required(ErrorMessage = "Please enter last name")]
- [Display(Name = "Last Name")]
- public string LastName { get; set; }
- [Required(ErrorMessage = "Please enter age")]
- public Nullable<int> Age { get; set; }
- [Required(ErrorMessage = "Please enter position")]
- public string Position { get; set; }
- [Required(ErrorMessage = "Please enter office")]
- public string Office { get; set; }
- [Required(ErrorMessage = "Please enter salary")]
- public Nullable<int> Salary { get; set; }
- }
- }
Step 6
Right-click on project >> “Add” a folder >> name it Repositories.
Step 7
Right-click on created Repositories folder and “Add” an interface. Name it as IEmployeeRepository.cs. Write the following code.
- using MvcRepositoryDesignPattern_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace MvcRepositoryDesignPattern_Demo.Repositories
- {
- public interface IEmployeeRepository
- {
- IEnumerable<Employee> GetEmployees();
- Employee GetEmployeeById(int id);
- void NewEmployee(Employee employee);
- void UpdateEmployee(Employee employee);
- void DeleteEmployee(int id);
- void Save();
- }
- }
Step 8
Similarly, add another class and name it EmployeeRepository.cs. Write the following code in it.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using MvcRepositoryDesignPattern_Demo.Models;
- using System.Data.Entity;
- namespace MvcRepositoryDesignPattern_Demo.Repositories
- {
- public class EmployeeRepository : IEmployeeRepository
- {
- private readonly EmployeeContext _dbContext;
- public EmployeeRepository()
- {
- _dbContext = new EmployeeContext();
- }
- public EmployeeRepository(EmployeeContext context)
- {
- _dbContext = context;
- }
- public IEnumerable<Employee> GetEmployees()
- {
- return _dbContext.Employees.ToList();
- }
- public Employee GetEmployeeById(int id)
- {
- return _dbContext.Employees.Find(id);
- }
- public void NewEmployee(Employee employee)
- {
- _dbContext.Employees.Add(employee);
- Save();
- }
- public void UpdateEmployee(Employee employee)
- {
- _dbContext.Entry(employee).State = EntityState.Modified;
- }
- public void DeleteEmployee(int id)
- {
- var employee = _dbContext.Employees.Find(id);
- if (employee != null) _dbContext.Employees.Remove(employee);
- }
- public void Save()
- {
- _dbContext.SaveChanges();
- }
- private bool _disposed = false;
- protected virtual void Dispose(bool disposing)
- {
- if (!this._disposed)
- {
- if (disposing)
- {
- _dbContext.Dispose();
- }
- }
- this._disposed = true;
- }
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- }
- }
Step 9
Right-click on the Controllers folder and add a new controller.

A window will appear. Choose MVC5 Controller-Empty and click "Add".

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.

The complete code for HomeController.
- using MvcRepositoryDesignPattern_Demo.Models;
- using MvcRepositoryDesignPattern_Demo.Repositories;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MvcRepositoryDesignPattern_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly IEmployeeRepository _employeeRepository;
- public HomeController()
- {
- _employeeRepository = new EmployeeRepository(new EmployeeContext());
- }
- public HomeController(IEmployeeRepository employeeRepository)
- {
- _employeeRepository = employeeRepository;
- }
- public ActionResult Index()
- {
- var employee = _employeeRepository.GetEmployees();
- return View(employee);
- }
- public ActionResult Details(int id)
- {
- var employee= _employeeRepository.GetEmployeeById(id);
- return View(employee);
- }
- public ActionResult Create()
- {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(Employee employee)
- {
- if (ModelState.IsValid)
- {
- _employeeRepository.NewEmployee(employee);
- _employeeRepository.Save();
- return RedirectToAction("Index");
- }
- return View();
- }
- [HttpGet]
- public ActionResult Edit(int id)
- {
- var employee = _employeeRepository.GetEmployeeById(id);
- return View(employee);
- }
- [HttpPost]
- public ActionResult Edit(Employee employee)
- {
- if (ModelState.IsValid)
- {
- _employeeRepository.UpdateEmployee(employee);
- _employeeRepository.Save();
- return RedirectToAction("Index", "Home");
- }
- else
- {
- return View(employee);
- }
- }
- [HttpGet]
- public ActionResult Delete(int id)
- {
- var employee=_employeeRepository.GetEmployeeById(id);
- return View(employee);
- }
- [HttpPost]
- public ActionResult ConfirmDelete(int id)
- {
- _employeeRepository.DeleteEmployee(id);
- _employeeRepository.Save();
- return RedirectToAction("Index","Home");
- }
- }
- }







milind moreyPosted Sep 2, 2022, 8:25 AM
Well structured Program, Easy to understand, Thank you Farhan !
Faheem AhmadPosted Dec 20, 2020, 5:05 PM
Great explanation. Thanks Farhan.
Akshay PPosted Jun 19, 2020, 2:03 AM
Can you please help me with datetimepicker and drop down control in CRUD operation in mvc 5 using repository design pattern Thanks
Anthony TanPosted Oct 20, 2019, 12:08 AM
I got "does not implement interface member" error. and not sure what is the problem :(
Chittaranjan SwainPosted Sep 11, 2019, 7:58 AM
How to use Ado.Net in Repository pattern? Give any solution link?
humayoun kabirPosted Jul 12, 2019, 6:33 AM
@Farhan , nice article , but i think HttpPost delete should not work until you declare like this given below: [HttpPost] [ActionName("Delete")] public ActionResult ConfirmDelete(int id) { _employeeRepository.DeleteEmployee(id); _employeeRepository.Save(); return RedirectToAction("Index", "Home"); }
Amit MohantyPosted Jul 1, 2019, 7:13 AM
Nice article..