Repository Pattern is used to create an abstraction layer between data access layer and business logic layer of an application. Repository directly communicates with data access layer [DAL] and gets the data and provides it to business logic layer [BAL]. The main advantage to use repository pattern to isolate the data access logic and business logic, so that if you make changes in any of this logic that cannot effect directly on other logic.
Today, I am going to explain how to use repository pattern in ASP.NET MVC with EntityFramework.
Step 1:
- Start Visual Studio 2013 or 2012.
- Create a new project -> Web -> Visual Studio 2012.
- Select ASP.NET MVC 4 Web Application.
- Provide the Name and Location for the project and click Next.
- Choose Basic template as project template and click OK.
Step 2:
Create a EmployeeContext.cs and Employee.cs entity class inside Model folder for database factory. You can create database and table manually or if you use my approach it will create database and table automatically when you run the application first time because I have used here code first approach.
Employee.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Linq;
- using System.Web;
-
- namespace RepositoryWithMVC.Models
- {
- [Table("Employee")]
- public class Employee
- {
- [Key]
- public int EmployeeId
- {
- get;
- set;
- }
-
- [Display(Name = "Employee Name")]
- [Required(ErrorMessage = "Name is required")]
- public string EmployeeName
- {
- get;
- set;
- }
-
- [Display(Name = "Address")]
- [Required(ErrorMessage = "Address is required")]
- public string Address
- {
- get;
- set;
- }
-
- [Required(ErrorMessage = "Email Id is required")]
- public string EmailId
- {
- get;
- set;
- }
- }
- }
EmployeeContext.cs - using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Web;
-
- namespace RepositoryWithMVC.Models
- {
- public class EmployeeContext: DbContext
- {
- public EmployeeContext(): base("DefaultConnection") {}
- public DbSet < Employee > Employees
- {
- get;
- set;
- }
- }
- }
Web.Config
- <connectionStrings>
- <add name="DefaultConnection" connectionString="data source=(local); database=Demodb; user id=sa; password=xyz;" providerName="System.Data.SqlClient" />
- </connectionStrings>
Step 3:
Create a folder with name “Repository” inside your project. Add an interface and a class respectively
IEmployeeRepository.cs and
EmployeeRepository.cs. IEmployeeRepository.cs - using RepositoryWithMVC.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace RepositoryWithMVC.Repository
- {
- public interface IEmployeeRepository: IDisposable
- {
- IEnumerable < Employee > GetAllEmployee();
- Employee GetEmployeeById(int studentId);
- int AddEmployee(Employee employeeEntity);
- int UpdateEmployee(Employee employeeEntity);
- void DeleteEmployee(int employeeId);
- }
- }
EmployeeRepository.cs
- using RepositoryWithMVC.Models;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
-
- namespace RepositoryWithMVC.Repository
- {
- public class EmployeeRepository: IEmployeeRepository
- {
- private readonly EmployeeContext _context;
-
- public EmployeeRepository(EmployeeContext context)
- {
- _context = context;
- }
-
- public IEnumerable < Employee > GetAllEmployee()
- {
- return _context.Employees.ToList();
- }
- public Employee GetEmployeeById(int studentId)
- {
- return _context.Employees.Find(studentId);
- }
-
- public int AddEmployee(Employee employeeEntity)
-
- {
- int result = -1;
-
- if (employeeEntity != null)
- {
- _context.Employees.Add(employeeEntity);
- _context.SaveChanges();
- result = employeeEntity.EmployeeId;
- }
- return result;
-
- }
- public int UpdateEmployee(Employee employeeEntity)
- {
- int result = -1;
-
- if (employeeEntity != null)
- {
- _context.Entry(employeeEntity).State = EntityState.Modified;
- _context.SaveChanges();
- result = employeeEntity.EmployeeId;
- }
- return result;
- }
- public void DeleteEmployee(int employeeId)
- {
- Employee employeeEntity = _context.Employees.Find(employeeId);
- _context.Employees.Remove(employeeEntity);
- _context.SaveChanges();
-
- }
-
- private bool disposed = false;
-
- protected virtual void Dispose(bool disposing)
- {
- if (!this.disposed)
- {
- if (disposing)
- {
- _context.Dispose();
- }
- }
- this.disposed = true;
- }
-
- public void Dispose()
- {
- Dispose(true);
-
- GC.SuppressFinalize(this);
- }
- }
- }
Step 4:
Add a EmployeeController which directly interact with Repository.
- using RepositoryWithMVC.Models;
- using RepositoryWithMVC.Repository;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace RepositoryWithMVC.Controllers
- {
- public class EmployeeController: Controller
- {
- private IEmployeeRepository _employeeRepository;
-
- public EmployeeController()
- {
- _employeeRepository = new EmployeeRepository(new Models.EmployeeContext());
- }
- public EmployeeController(IEmployeeRepository employeeRepository)
- {
- _employeeRepository = employeeRepository;
- }
-
- public ActionResult Index()
- {
- var model = _employeeRepository.GetAllEmployee();
- return View(model);
- }
-
- public ActionResult AddEmployee()
- {
- if (TempData["Failed"] != null)
- {
- ViewBag.Failed = "Add Employee Failed";
- }
- return View();
- }
-
- [HttpPost]
- public ActionResult AddEmployee(Employee model)
- {
- if (ModelState.IsValid) {
- int result = _employeeRepository.AddEmployee(model);
- if (result > 0) {
- return RedirectToAction("Index", "Employee");
- } else {
- TempData["Failed"] = "Failed";
- return RedirectToAction("AddEmployee", "Employee");
- }
- }
- return View();
- }
-
- public ActionResult EditEmployee(int EmployeeId)
- {
- if (TempData["Failed"] != null) {
- ViewBag.Failed = "Edit Employee Failed";
- }
- Employee model = _employeeRepository.GetEmployeeById(EmployeeId);
- return View(model);
- }
-
- [HttpPost]
- public ActionResult EditEmployee(Employee model)
- {
- if (ModelState.IsValid) {
- int result = _employeeRepository.UpdateEmployee(model);
- if (result > 0) {
- return RedirectToAction("Index", "Employee");
- } else {
-
- return RedirectToAction("Index", "Employee");
- }
- }
- return View();
- }
-
-
- public ActionResult DeleteEmployee(int EmployeeId)
- {
- Employee model = _employeeRepository.GetEmployeeById(EmployeeId);
- return View(model);
- }
-
- [HttpPost]
- public ActionResult DeleteEmployee(Employee model)
- {
- if (TempData["Failed"] != null) {
- ViewBag.Failed = "Delete Employee Failed";
- }
- _employeeRepository.DeleteEmployee(model.EmployeeId);
- return RedirectToAction("Index", "Employee");
- }
-
- }
- }
Step 5: Create View for the Controller action method like Index, EditEmployee, DeleteEmployee, etc.
Index.cshtml
- @model IEnumerable < RepositoryWithMVC.Models.Employee >
-
- @ {
- ViewBag.Title = "Index";
- } < div align = "center" >
- < h3 > Employee Management < /h3> < span > < a href = "@Url.Action("
- AddEmployee ","
- Employee ")" > Add Employee < /a></span >
- < br / >
- < br / >
- < table cellpadding = "5"
- border = "1" >
- < tr style = "background-color:#808080; color:white;" >
- < td >
- Employee Id < /td> < td >
- Name < /td> < td >
- Address < /td> < td >
- Email Id < /td> < td >
- Action < /td> < /tr>
- @foreach(var emp in Model) { < tr >
- < td >
- @emp.EmployeeId < /td> < td >
- @emp.EmployeeName < /td> < td >
- @emp.Address < /td> < td >
- @emp.EmailId < /td> < td >
- < a href = "@Url.Action("
- EditEmployee ", "
- Employee ", new { @EmployeeId = emp.EmployeeId })" > Edit < /a> < a href = "@Url.Action("
- DeleteEmployee ", "
- Employee ", new { @EmployeeId = emp.EmployeeId })" > Delete < /a> < /td> < /tr>
-
- } < /table> < /div>
AddEmployee.cshtml
- @model RepositoryWithMVC.Models.Employee
- @ {
-
- ViewBag.Title = "AddEmployee";
- }
-
- < div align = "center" >
- < h3 > Employee Management < /h3> < br / >
- < b > Add New Employee < /b> < br / >
- < br / >
-
- @using(Html.BeginForm("AddEmployee", "Employee", FormMethod.Post)) { < table >
- < tr >
- < td colspan = "2" >
- @if(ViewBag.Failed != null) { < span style = "color:red;" > @ViewBag.Failed < /span>
- } < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.EmployeeName) < /td> < td >
- @Html.TextBoxFor(e => e.EmployeeName) < br / >
- @Html.ValidationMessageFor(e => e.EmployeeName, null, new {
- style = "color:red;"
- }) < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.Address) < /td> < td >
- @Html.TextBoxFor(e => e.Address) < br / >
- @Html.ValidationMessageFor(e => e.EmployeeName, null, new {
- style = "color:red;"
- }) < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.EmailId) < /td> < td >
- @Html.TextBoxFor(e => e.EmailId) < br / >
- @Html.ValidationMessageFor(e => e.EmployeeName, null, new {
- style = "color:red;"
- }) < /td> < /tr> < tr >
- < td colspan = "2"
- align = "center" >
- < br / >
- < input type = "submit"
- value = "Submit" / >
- < /td> < /tr> < /table>
- } < /div>
EditEmployee.cshtml - @model RepositoryWithMVC.Models.Employee
- @ {
-
- ViewBag.Title = "Edit Employee";
- }
-
- < div align = "center" >
- < h3 > Employee Management < /h3> < br / >
- < b > Edit Employee < /b> < br / >
- < br / >
-
- @using(Html.BeginForm("EditEmployee", "Employee", FormMethod.Post))
- {
- @Html.HiddenFor(e => e.EmployeeId) < table >
- < tr >
- < td colspan = "2" >
- @if(ViewBag.Failed != null) { < span style = "color:red;" > @ViewBag.Failed < /span>
- } < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.EmployeeName) < /td> < td >
- @Html.TextBoxFor(e => e.EmployeeName) < br / >
- @Html.ValidationMessageFor(e => e.EmployeeName, null, new
- {
- style = "color:red;"
- }) < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.Address) < /td> < td >
- @Html.TextBoxFor(e => e.Address) < br / >
- @Html.ValidationMessageFor(e => e.EmployeeName, null, new
- {
- style = "color:red;"
- }) < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.EmailId) < /td> < td >
- @Html.TextBoxFor(e => e.EmailId) < br / >
- @Html.ValidationMessageFor(e => e.EmployeeName, null, new
- {
- style = "color:red;"
- }) < /td> < /tr> < tr >
- < td colspan = "2"
- align = "center" >
- < br / >
- < input type = "submit"
- value = "Update" / >
- < /td> < /tr> < /table>
- } < /div>
DeleteEmployee.cshtml
- @model RepositoryWithMVC.Models.Employee
- @ {
-
- ViewBag.Title = "Delete Employee";
- }
-
- < div align = "center" >
- < h3 > Employee Management < /h3> < br / >
-
-
- @using(Html.BeginForm("DeleteEmployee", "Employee", FormMethod.Post))
- {
- @Html.HiddenFor(e => e.EmployeeId) < table border = "1"
- cellpadding = "10" >
- < tr >
- < td colspan = "2"
- align = "center" >
- < b > Delete Employee < /b>
- @if(ViewBag.Failed != null) { < span style = "color:red;" > @ViewBag.Failed < /span>
- } < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.EmployeeName) < /td> < td >
- @Html.TextBoxFor(e => e.EmployeeName, new
- {
- @readonly = "readonly"
- })
-
- < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.Address) < /td> < td >
- @Html.TextBoxFor(e => e.Address, new
- {
- @readonly = "readonly"
- })
-
- < /td> < /tr> < tr >
- < td >
- @Html.LabelFor(e => e.EmailId) < /td> < td >
- @Html.TextBoxFor(e => e.EmailId, new
- {
- @readonly = "readonly"
- })
-
- < /td> < /tr> < tr >
- < td colspan = "2"
- align = "center" >
- < br / >
- < input type = "submit"
- value = "Delete" / >
- < /td> < /tr> < /table>
- } < /div>
Note: Change in RouteConfig.cs controller name from home to employee in default.
Thanks for reading this article, hope you enjoyed it.