Repository Pattern With ASP.NET MVC And Entity Framework

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace RepositoryWithMVC.Models   
  9. {  
  10.     [Table("Employee")]  
  11.     public class Employee   
  12.     {  
  13.         [Key]  
  14.         public int EmployeeId   
  15.         {  
  16.             get;  
  17.             set;  
  18.         }  
  19.   
  20.         [Display(Name = "Employee Name")]  
  21.         [Required(ErrorMessage = "Name is required")]  
  22.         public string EmployeeName   
  23.         {  
  24.             get;  
  25.             set;  
  26.         }  
  27.   
  28.         [Display(Name = "Address")]  
  29.         [Required(ErrorMessage = "Address is required")]  
  30.         public string Address   
  31.         {  
  32.             get;  
  33.             set;  
  34.         }  
  35.   
  36.         [Required(ErrorMessage = "Email Id is required")]  
  37.         public string EmailId   
  38.         {  
  39.             get;  
  40.             set;  
  41.         }  
  42.     }  
  43. }  
EmployeeContext.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace RepositoryWithMVC.Models   
  8. {  
  9.     public class EmployeeContext: DbContext   
  10.     {  
  11.         public EmployeeContext(): base("DefaultConnection") {}  
  12.         public DbSet < Employee > Employees   
  13.         {  
  14.             get;  
  15.             set;  
  16.         }  
  17.     }  
  18. }  
Web.Config
  1. <connectionStrings>  
  2.     <add name="DefaultConnection" connectionString="data source=(local); database=Demodb; user id=sa; password=xyz;" providerName="System.Data.SqlClient" />  
  3. </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
  1. using RepositoryWithMVC.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace RepositoryWithMVC.Repository   
  8. {  
  9.     public interface IEmployeeRepository: IDisposable   
  10.     {  
  11.         IEnumerable < Employee > GetAllEmployee();  
  12.         Employee GetEmployeeById(int studentId);  
  13.         int AddEmployee(Employee employeeEntity);  
  14.         int UpdateEmployee(Employee employeeEntity);  
  15.         void DeleteEmployee(int employeeId);  
  16.     }  
  17. }  
EmployeeRepository.cs
  1. using RepositoryWithMVC.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace RepositoryWithMVC.Repository   
  9. {  
  10.     public class EmployeeRepository: IEmployeeRepository   
  11.     {  
  12.         private readonly EmployeeContext _context;  
  13.         
  14.         public EmployeeRepository(EmployeeContext context)   
  15.         {  
  16.             _context = context;  
  17.         }  
  18.   
  19.         public IEnumerable < Employee > GetAllEmployee()  
  20.         {  
  21.             return _context.Employees.ToList();  
  22.         }  
  23.         public Employee GetEmployeeById(int studentId)  
  24.         {  
  25.             return _context.Employees.Find(studentId);  
  26.         }  
  27.   
  28.         public int AddEmployee(Employee employeeEntity)  
  29.           
  30.         {  
  31.             int result = -1;  
  32.             
  33.             if (employeeEntity != null)  
  34.             {  
  35.                 _context.Employees.Add(employeeEntity);  
  36.                 _context.SaveChanges();  
  37.                 result = employeeEntity.EmployeeId;  
  38.             }  
  39.             return result;  
  40.   
  41.         }  
  42.         public int UpdateEmployee(Employee employeeEntity)   
  43.         {  
  44.             int result = -1;  
  45.             
  46.             if (employeeEntity != null)   
  47.             {  
  48.                 _context.Entry(employeeEntity).State = EntityState.Modified;  
  49.                 _context.SaveChanges();  
  50.                 result = employeeEntity.EmployeeId;  
  51.             }  
  52.             return result;  
  53.         }  
  54.         public void DeleteEmployee(int employeeId)   
  55.         {  
  56.             Employee employeeEntity = _context.Employees.Find(employeeId);  
  57.             _context.Employees.Remove(employeeEntity);  
  58.             _context.SaveChanges();  
  59.   
  60.         }  
  61.   
  62.         private bool disposed = false;  
  63.   
  64.         protected virtual void Dispose(bool disposing)   
  65.         {  
  66.             if (!this.disposed)  
  67.             {  
  68.                 if (disposing)   
  69.                 {  
  70.                     _context.Dispose();  
  71.                 }  
  72.             }  
  73.             this.disposed = true;  
  74.         }  
  75.   
  76.         public void Dispose()   
  77.         {  
  78.             Dispose(true);  
  79.             
  80.             GC.SuppressFinalize(this);  
  81.         }  
  82.     }  
  83. }  
Step 4:

Add a EmployeeController which directly interact with Repository.
  1. using RepositoryWithMVC.Models;  
  2. using RepositoryWithMVC.Repository;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace RepositoryWithMVC.Controllers   
  10. {  
  11.     public class EmployeeController: Controller   
  12.     {  
  13.         private IEmployeeRepository _employeeRepository;  
  14.   
  15.         public EmployeeController()   
  16.         {  
  17.             _employeeRepository = new EmployeeRepository(new Models.EmployeeContext());  
  18.         }  
  19.         public EmployeeController(IEmployeeRepository employeeRepository)   
  20.         {  
  21.             _employeeRepository = employeeRepository;  
  22.         }  
  23.   
  24.         public ActionResult Index()   
  25.         {  
  26.             var model = _employeeRepository.GetAllEmployee();  
  27.             return View(model);  
  28.         }  
  29.   
  30.         public ActionResult AddEmployee()   
  31.         {  
  32.             if (TempData["Failed"] != null)   
  33.             {  
  34.                 ViewBag.Failed = "Add Employee Failed";  
  35.             }  
  36.             return View();  
  37.         }  
  38.   
  39.         [HttpPost]  
  40.         public ActionResult AddEmployee(Employee model)   
  41.         {  
  42.             if (ModelState.IsValid) {  
  43.                 int result = _employeeRepository.AddEmployee(model);  
  44.                 if (result > 0) {  
  45.                     return RedirectToAction("Index""Employee");  
  46.                 } else {  
  47.                     TempData["Failed"] = "Failed";  
  48.                     return RedirectToAction("AddEmployee""Employee");  
  49.                 }  
  50.             }  
  51.             return View();  
  52.         }  
  53.   
  54.         public ActionResult EditEmployee(int EmployeeId)   
  55.         {  
  56.             if (TempData["Failed"] != null) {  
  57.                 ViewBag.Failed = "Edit Employee Failed";  
  58.             }  
  59.             Employee model = _employeeRepository.GetEmployeeById(EmployeeId);  
  60.             return View(model);  
  61.         }  
  62.   
  63.         [HttpPost]  
  64.         public ActionResult EditEmployee(Employee model)  
  65.         {  
  66.             if (ModelState.IsValid) {  
  67.                 int result = _employeeRepository.UpdateEmployee(model);  
  68.                 if (result > 0) {  
  69.                     return RedirectToAction("Index""Employee");  
  70.                 } else {  
  71.   
  72.                     return RedirectToAction("Index""Employee");  
  73.                 }  
  74.             }  
  75.             return View();  
  76.         }  
  77.   
  78.   
  79.         public ActionResult DeleteEmployee(int EmployeeId)   
  80.         {  
  81.             Employee model = _employeeRepository.GetEmployeeById(EmployeeId);  
  82.             return View(model);  
  83.         }  
  84.   
  85.         [HttpPost]  
  86.         public ActionResult DeleteEmployee(Employee model)  
  87.         {  
  88.             if (TempData["Failed"] != null) {  
  89.                 ViewBag.Failed = "Delete Employee Failed";  
  90.             }  
  91.             _employeeRepository.DeleteEmployee(model.EmployeeId);  
  92.             return RedirectToAction("Index""Employee");  
  93.         }  
  94.   
  95.     }  
  96. }  
Step 5:

Create View for the Controller action method like Index, EditEmployee, DeleteEmployee, etc.

Index.cshtml
  1. @model IEnumerable < RepositoryWithMVC.Models.Employee >  
  2.   
  3.     @ {  
  4.         ViewBag.Title = "Index";  
  5.     } < div align = "center" >  
  6.     < h3 > Employee Management < /h3> < span > < a href = "@Url.Action("  
  7. AddEmployee ","  
  8. Employee ")" > Add Employee < /a></span >  
  9.     < br / >  
  10.     < br / >  
  11.     < table cellpadding = "5"  
  12. border = "1" >  
  13.     < tr style = "background-color:#808080; color:white;" >  
  14.     < td >  
  15.     Employee Id < /td> < td >  
  16.     Name < /td> < td >  
  17.     Address < /td> < td >  
  18.     Email Id < /td> < td >  
  19.     Action < /td> < /tr>  
  20. @foreach(var emp in Model) { < tr >  
  21.         < td >  
  22.         @emp.EmployeeId < /td> < td >  
  23.         @emp.EmployeeName < /td> < td >  
  24.         @emp.Address < /td> < td >  
  25.         @emp.EmailId < /td> < td >  
  26.         < a href = "@Url.Action("  
  27.     EditEmployee ", "  
  28.     Employee ", new { @EmployeeId = emp.EmployeeId })" > Edit < /a> < a href = "@Url.Action("  
  29.     DeleteEmployee ", "  
  30.     Employee ", new { @EmployeeId = emp.EmployeeId })" > Delete < /a> < /td> < /tr>  
  31.   
  32. } < /table> < /div>  
AddEmployee.cshtml
  1. @model RepositoryWithMVC.Models.Employee  
  2. @ {  
  3.   
  4.     ViewBag.Title = "AddEmployee";  
  5. }  
  6.   
  7. < div align = "center" >  
  8.     < h3 > Employee Management < /h3> < br / >  
  9.     < b > Add New Employee < /b> < br / >  
  10.     < br / >  
  11.   
  12.     @using(Html.BeginForm("AddEmployee""Employee", FormMethod.Post)) { < table >  
  13.             < tr >  
  14.             < td colspan = "2" >  
  15.             @if(ViewBag.Failed != null) { < span style = "color:red;" > @ViewBag.Failed < /span>  
  16.             } < /td> < /tr> < tr >  
  17.             < td >  
  18.             @Html.LabelFor(e => e.EmployeeName) < /td> < td >  
  19.             @Html.TextBoxFor(e => e.EmployeeName) < br / >  
  20.             @Html.ValidationMessageFor(e => e.EmployeeName, nullnew {  
  21.                 style = "color:red;"  
  22.             }) < /td> < /tr> < tr >  
  23.             < td >  
  24.             @Html.LabelFor(e => e.Address) < /td> < td >  
  25.             @Html.TextBoxFor(e => e.Address) < br / >  
  26.             @Html.ValidationMessageFor(e => e.EmployeeName, nullnew {  
  27.                 style = "color:red;"  
  28.             }) < /td> < /tr> < tr >  
  29.             < td >  
  30.             @Html.LabelFor(e => e.EmailId) < /td> < td >  
  31.             @Html.TextBoxFor(e => e.EmailId) < br / >  
  32.             @Html.ValidationMessageFor(e => e.EmployeeName, nullnew {  
  33.                 style = "color:red;"  
  34.             }) < /td> < /tr> < tr >  
  35.             < td colspan = "2"  
  36.         align = "center" >  
  37.             < br / >  
  38.             < input type = "submit"  
  39.         value = "Submit" / >  
  40.             < /td> < /tr> < /table>  
  41.     } < /div>  
EditEmployee.cshtml
  1. @model RepositoryWithMVC.Models.Employee  
  2. @ {  
  3.   
  4.     ViewBag.Title = "Edit Employee";  
  5. }  
  6.   
  7. < div align = "center" >  
  8.     < h3 > Employee Management < /h3> < br / >  
  9.     < b > Edit Employee < /b> < br / >  
  10.     < br / >  
  11.   
  12.     @using(Html.BeginForm("EditEmployee""Employee", FormMethod.Post))   
  13.     {  
  14.         @Html.HiddenFor(e => e.EmployeeId) < table >  
  15.             < tr >  
  16.             < td colspan = "2" >  
  17.             @if(ViewBag.Failed != null) { < span style = "color:red;" > @ViewBag.Failed < /span>  
  18.             } < /td> < /tr> < tr >  
  19.             < td >  
  20.             @Html.LabelFor(e => e.EmployeeName) < /td> < td >  
  21.             @Html.TextBoxFor(e => e.EmployeeName) < br / >  
  22.             @Html.ValidationMessageFor(e => e.EmployeeName, nullnew   
  23.                                        {  
  24.                 style = "color:red;"  
  25.             }) < /td> < /tr> < tr >  
  26.             < td >  
  27.             @Html.LabelFor(e => e.Address) < /td> < td >  
  28.             @Html.TextBoxFor(e => e.Address) < br / >  
  29.             @Html.ValidationMessageFor(e => e.EmployeeName, nullnew  
  30.                                        {  
  31.                 style = "color:red;"  
  32.             }) < /td> < /tr> < tr >  
  33.             < td >  
  34.             @Html.LabelFor(e => e.EmailId) < /td> < td >  
  35.             @Html.TextBoxFor(e => e.EmailId) < br / >  
  36.             @Html.ValidationMessageFor(e => e.EmployeeName, nullnew  
  37.                                        {  
  38.                 style = "color:red;"  
  39.             }) < /td> < /tr> < tr >  
  40.             < td colspan = "2"  
  41.         align = "center" >  
  42.             < br / >  
  43.             < input type = "submit"  
  44.         value = "Update" / >  
  45.             < /td> < /tr> < /table>  
  46.     } < /div>  
DeleteEmployee.cshtml
  1. @model RepositoryWithMVC.Models.Employee  
  2. @ {  
  3.   
  4.     ViewBag.Title = "Delete Employee";  
  5. }  
  6.   
  7. < div align = "center" >  
  8.     < h3 > Employee Management < /h3> < br / >  
  9.   
  10.   
  11.     @using(Html.BeginForm("DeleteEmployee""Employee", FormMethod.Post))  
  12.     {  
  13.         @Html.HiddenFor(e => e.EmployeeId) < table border = "1"  
  14.         cellpadding = "10" >  
  15.             < tr >  
  16.             < td colspan = "2"  
  17.         align = "center" >  
  18.             < b > Delete Employee < /b>  
  19.         @if(ViewBag.Failed != null) { < span style = "color:red;" > @ViewBag.Failed < /span>  
  20.             } < /td> < /tr> < tr >  
  21.             < td >  
  22.             @Html.LabelFor(e => e.EmployeeName) < /td> < td >  
  23.             @Html.TextBoxFor(e => e.EmployeeName, new   
  24.                              {  
  25.                 @readonly = "readonly"  
  26.             })  
  27.   
  28.         < /td> < /tr> < tr >  
  29.             < td >  
  30.             @Html.LabelFor(e => e.Address) < /td> < td >  
  31.             @Html.TextBoxFor(e => e.Address, new   
  32.                              {  
  33.                 @readonly = "readonly"  
  34.             })  
  35.   
  36.         < /td> < /tr> < tr >  
  37.             < td >  
  38.             @Html.LabelFor(e => e.EmailId) < /td> < td >  
  39.             @Html.TextBoxFor(e => e.EmailId, new  
  40.                              {  
  41.                 @readonly = "readonly"  
  42.             })  
  43.   
  44.         < /td> < /tr> < tr >  
  45.             < td colspan = "2"  
  46.         align = "center" >  
  47.             < br / >  
  48.             < input type = "submit"  
  49.         value = "Delete" / >  
  50.             < /td> < /tr> < /table>  
  51.     } < /div>  
Note: Change in RouteConfig.cs controller name from home to employee in default.

Thanks for reading this article, hope you enjoyed it.


Similar Articles