An application's data access layer and business logic layer are separated by an abstraction layer that is created using the repository pattern. The business logic layer (BAL) receives data from the repository via direct communication with the data access layer (DAL). The primary benefit of employing a repository pattern is its ability to separate the business and data access logic, preventing modifications to one from having an immediate impact on the other.


I'll go over how to leverage repository patterns in EntityFramework-powered ASP.NET MVC today.

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 the project template and click OK.


Step 2. Create an EmployeeContext.cs and Employee.cs entity class inside the Model folder for the database factory. You can create a database and table manually or if you use my approach it will create a database and table automatically when you run the application the 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 the 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 an EmployeeController that directly interacts with the 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 a 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.Address, 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.EmailId, 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.Address, 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.EmailId, 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.