---
title: "Repository Pattern in MVC"  
description: "Repository act as a middle man between the rest of the application and the data access logic. A repository isolates all the data access code from the"  
author: "Jonas Stuart"  
published: 2017-01-17  
updated: 2017-12-20  
canonical: https://www.mindstick.com/articles/12232/repository-pattern-in-mvc  
category: "c#"  
tags: ["c#", "mvc"]  
reading_time: 3 minutes  

---

# Repository Pattern in MVC

Repository act as a middle man between the rest of the [application](https://www.mindstick.com/articles/12824/calculator-application-in-android) and the [data access](https://www.mindstick.com/forum/473/what-are-the-data-access-namespaces-in-dot-net) logic. A repository isolates all the data access code from the rest of the application. In doing so you are benefited by having a single point of change in case modification. **It is easier to change** in repository because it is another class separate from the application. So we can easily change when necessary without code affecting.

A repository does at least five thing Insert, select by Id, Select All, delete, save.By using repository pattern in our application we get [code reusability](https://www.mindstick.com/articles/337478/the-role-of-design-patterns-in-enhancing-code-reusability) and maximum code testability. In this article we will do [crud operation](https://www.mindstick.com/articles/12249/crud-operation-in-border-layout-on-grid) through repository pattern. I will use generic repository pattern for all operation.

For generic repository we will add a class in the model folder and add the following code.

```
using System;usingSystem.Collections.Generic;using System.Linq;using System.Web;using Manish.Models; namespace Manish.Models{    public  interface IRepository<T> where T : class    {                IEnumerable<T> SelectAll();        T SelectByID(object id);        void Insert(T obj);        void Update(T obj);        void Delete(object Id);        }}
```

In this class I have make the Interface of public type with T type.

Now add another class in the model folder and name it Repository and Inherit IRepository in it

```
using System;usingSystem.Collections.Generic;using System.Linq;using System.Web;using Manish.Models;using System.Data.Entity;using System.Data; namespace Manish.Models{    public class Repository<T>:IRepository<T> where T:class    {        private testdataEntities db = null;        private DbSet<T> table = null;       public Repository()        {            this.db = new testdataEntities();            table = db.Set<T>();        }       public Repository(testdataEntities db)        {            this.db = db;            table = db.Set<T>();        }         public IEnumerable<T> SelectAll()        {            return table.ToList();        }         public T SelectByID(object id)        {            return table.Find(id);        }         public void Insert(T obj)        {            table.Add(obj);            db.SaveChanges();        }         public void Update(T obj)        {            table.Attach(obj);            db.Entry(obj).State = EntityState.Modified;            db.SaveChanges();        }         public void Delete(object Id)        {            T existing = table.Find(Id);            table.Remove(existing);            db.SaveChanges();              }          }   }
```

In this Repository class I have defined all the method of IRepository class for Implementation. now add one another [class name](https://www.mindstick.com/forum/12871/how-to-get-class-name) it DML Repository for setting the property for IRepository.

```
using System;usingSystem.Collections.Generic;using System.Linq;using System.Web; namespace Manish.Models{    public class DMLRepository    {        public IRepository<Student> Student        {            get            {                return new Repository<Student>();            }        }        public IRepository<Login> Login        {            get            {                return new Repository<Login>();            }        }    }}
```

***Now add a class in the [controller](https://www.mindstick.com/blog/273/passing-values-from-controller-to-view-in-asp-dot-net-mvc) folder name it base controller. And add the following code.***

```
using System;usingSystem.Collections.Generic;using System.Linq;using System.Web;using Manish.Models;using Manish.Controllers;using System.Web.Mvc; namespace Manish.Controllers{    public class BaseController :Controller    {        protected DMLRepository Uow { get; set; }        public BaseController()        {            Uow = new DMLRepository();        }    }}
```

***Now in the home controller inherit base controller***

using System;

using

System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Manish.Controllers;

using Manish.Models;

using

System.Web.Security;

namespace Manish.Controllers

{

public class HomeController : BaseController

{

//

// GET: /Home/

public [ActionResult](https://www.mindstick.com/forum/33961/what-is-the-difference-between-actionresult-and-viewresult) Index()

{

ViewBag.Users =

Uow.Student.SelectAll();

return View();

}

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Index(Student model)

{

if (model.Id == 0)

{

Uow.Student.Insert(model);

}

else

{

Uow.Student.SelectByID(model.Id);

Uow.Student.Update(model);

}

ViewBag.Users =

Uow.Student.SelectAll();

return PartialView("studentlist");

}

public ActionResult Delete(int id)

{

Uow.Student.Delete(id);

ViewBag.Users =

Uow.Student.SelectAll();

return PartialView("studentlist");

}

public ActionResult Edit(int id)

{

var data = Uow.Student.SelectByID(id);

return Json(data, JsonRequestBehavior.AllowGet);

}

}

}

}

## *You can also visit these useful related post*

[Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC using Entity Framework](https://www.mindstick.com/Articles/12005/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-dot-net-mvc-using-entity-framework)

[What is Repository Pattern in ASP.NET MVC?](https://www.mindstick.com/Interview/1486/what-is-repository-pattern-in-asp-dot-net-mvc)

[Crud Operations Using Generic Repository Pattern in ASP.NET MVC 4](https://www.mindstick.com/Articles/1565/crud-operations-using-generic-repository-pattern-in-asp-dot-net-mvc-4)

***\***

---

Original Source: https://www.mindstick.com/articles/12232/repository-pattern-in-mvc

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
