MVC5 CRUD Using Generic Repository Pattern

dicon Download source code 7.86 MB

What does Repository mean?
Dictionary meaning: A place where things may be put for safekeeping.

Repository Pattern:
The Repository Pattern allows to centralise all data access logic in one place. It is a common construct to avoid duplication of data access logic throughout our application. The Repository pattern adds a separation layer between the data and business layers of an application.

IC340233

Generic Repository Pattern:
A generic(relating to) repository is often used with the ORM(entity framework) to speed up the process of creating a data layer.With generic feature, we can reduce the amount of code we need for common scenarios.

namespace WebApplication1.Repository
{
    interface IRepository : IDisposable where T : class
    {
        IEnumerable GetAll();

        T GetById(object Id);

        void Insert(T model);

        void Update(T model);

        void Delete(object id);

        void Save();
    }
}

Explanation:
interface IRepository
Show an interface of a generic repository of type T, which is a LINQ to SQL entity. It provides a basic interface with operations like Insert, Update, Delete, GetById and GetAll.

IDisposable
The IDisposable Interface, Provides a mechanism for releasing unmanaged resources.

where T : class

where T : class

This is constraining the generic parameter to a class.
The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

namespace WebApplication1.Repository
{
    public class GenericRepository : IRepository where T : class
    {

        Customer_Entities context = null;
        private DbSet entities = null;

        public GenericRepository(Customer_Entities context)
        {
            this.context = context;
            entities = context.Set();
        }

        public IEnumerable GetAll()
        {
            return this.entities.ToList();
        }

        public T GetById(object id)
        {
            return this.entities.Find(id);
        }

        public void Insert(T model)
        {
            context.Entry(model).State = EntityState.Added;
        }

        public void Update(T model)
        {
            context.Entry(model).State = EntityState.Modified;
        }

        public void Delete(object id)
        {
            T existing = this.entities.Find(id);
            this.entities.Remove(existing);
        }

        public void Save()
        {
            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);
        }
    }
}

Use of Generic Repository in  MVC-Application:

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        private GenericRepository CustRepository;
        public HomeController()
        {
            this.CustRepository = new GenericRepository(new Customer_Entities());
        }

        // GET: Home
        public ActionResult Index()
        {
            var test = CustRepository.GetAll();
            return View(test);
        }
        
        // GET: Insert
        public ActionResult Insert()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Insert(Customer model)
        {
            if (ModelState.IsValid)
            {
                CustRepository.Insert(model);
                CustRepository.Save();
            }
            return RedirectToAction("Index");
        }

        // GET: Delete
        public ActionResult Delete(int id)
        {
            this.CustRepository.Delete(id);
            CustRepository.Save();
            return RedirectToAction("Index");
        }

        // GET: Update
        public ActionResult Update(int id)
        {
            return View(this.CustRepository.GetById(id));
        }

        [HttpPost]
        public ActionResult Update(Customer model)
        {
            this.CustRepository.Update(model);
            CustRepository.Save();
            return RedirectToAction("Index");
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}

Explanation:

private GenericRepository CustRepository;

Declaration of GenericRepository reference.

public HomeController()
{
  this.CustRepository = new GenericRepository(new Customer_Entities());
}

In the constructor we initialize the object with GenericRepository class, passing Customer_Entities objct to the constructor as parameter 

Hope this will help 🙂

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

8 thoughts on “MVC5 CRUD Using Generic Repository Pattern”

    • vikash Kumar Mishra says:

      Reply

      but sir if i want to add the Business layer,Data access layer,repository layer with Ado.net entity frame work then how i can do that

  • Reply

    what if am going to retrieve result if combination of two table. like in LINQ we use join/inner join how could i retrieve it. and modified it?do i have to create another model for the result of two or more table?

  • Awesomely written article. Need and clean. Very precious about the topic.

Leave a Reply