---
title: "Generic Repository Pattern in C#."  
description: "Generic Repository Pattern in C#. with entity framework."  
author: "Anonymous User"  
published: 2018-09-13  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/13124/generic-repository-pattern-in-c-sharp  
category: "c#"  
tags: ["c#", "mvc", "mvc4", "entity framework"]  
reading_time: 14 minutes  

---

# Generic Repository Pattern in C#.

**Generic [Repository Pattern](https://www.mindstick.com/articles/1565/crud-operations-using-generic-repository-pattern-in-asp-dot-net-mvc-4)**

According to my own knowledge that Every project needs a better [architecture](https://www.mindstick.com/forum/155655/what-is-mvc-architecture) because it is the heart of any Projects. And wherefore I know that all programmers or [developers](https://www.mindstick.com/blog/302688/handling-errors-in-rust-a-comprehensive-guide-for-developers) need for a better architecture that reduces repetitive code and separates the [data access](https://www.mindstick.com/blog/301551/risks-and-challenges-of-data-access-and-sharing) layer and [business logic](https://answers.mindstick.com/qa/30543/what-is-business-logic) layer. So, we will use our [generic repository](https://www.mindstick.com/forum/33536/how-to-use-generic-repository-pattern-in-mvc-code-first) with MVC and [Entity framework](https://www.mindstick.com/forum/12875/how-to-use-object-query-with-a-where-and-to-retrieve-entity-record-entity-framework).

## First Step

Create a Database and their tables.

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/6ea86a82-37f3-4057-b310-dbf0a2fcb337.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/308b9ab9-6f36-4273-b4c2-c79193a9e2e8.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/6598bad5-506b-4423-8705-d1d2c550ceee.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/02a58880-842a-43e6-be33-7a93a02cd7f2.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/df35d78e-8592-4580-b062-e832fe2b48ab.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/30123482-4274-490f-96ae-08d7a431a2f4.png)\

## Second Step

Open [visual studio](https://www.mindstick.com/forum/12863/how-to-insert-a-video-in-asp-dot-net-web-page-in-visual-studio-2010) and add a new mvc (Empty) project.

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/f843d583-bea5-47bf-80a6-7a2f57b3a86e.png)

Then Add Entity Framework on it.

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/04579f5c-1fa7-4cb1-931e-69b99f5182e0.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/0e1be737-cb13-49ef-aa5f-de4c822d29df.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/90f15e37-f367-4e07-a2d8-c00233911295.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/2726df9a-7bf7-4eaf-93e7-4470f1462843.png)

## Third Step

Create _IAllRepository.cs file and write this code

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MvcApplication11.Models.DAL
{
    interface _IAllRepository<T> where T : class
    {
        IEnumerable<T> GetModel();
        T GetModelByID(int modelId);
        void InsertModel(T model);
        void DeleteModel(int modelID);
        void UpdateModel(T model);
        void Save();
    }
}
```

## Step 4

Call _IAllRepository in AllRepository.cs

```
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MvcApplication11.Models.DAL
{
    public class AllRepository<T> : _IAllRepository<T> where T : class
    {
        private DataContext _context;
        private IDbSet<T> dbEntity;

        public AllRepository()
        {
            _context = new DataContext();
            dbEntity = _context.Set<T>();
        }

        public IEnumerable<T> GetModel()
        {
            return dbEntity.ToList();
        }

        public T GetModelByID(int modelId)
        {
            return dbEntity.Find(modelId);
        }

        public void InsertModel(T model)
        {
            dbEntity.Add(model);
        }

        public void DeleteModel(int modelID)
        {
            T model = dbEntity.Find(modelID);
            dbEntity.Remove(model);
        }

        public void UpdateModel(T model)
        {
            _context.Entry(model).State = EntityState.Modified;
        }

        public void Save()
        {
            _context.SaveChanges();
        }
    }
}
```

## Step 5

Create Controller class for Contact table and controller name is "ContactsController"

```
using MvcApplication11.Models;
using MvcApplication11.Models.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication11.Controllers
{
    public class ContactsController : Controller
    {
        //
        // GET: /Contacts/
        private _IAllRepository<Contact> interfaceobj;
        public ContactsController()
        {
            this.interfaceobj = new AllRepository<Contact>();
        }

        public ActionResult Index()
        {
            return View(from m in interfaceobj.GetModel() select m);
        }

        //
        // GET: /Contacts/Details/5

        public ActionResult Details(int id)
        {
            Contact c = interfaceobj.GetModelByID(id);
            return View(c);
        }

        //
        // GET: /Contacts/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Contacts/Create

        [HttpPost]
        public ActionResult Create(Contact collection)
        {
            try
            {
                // TODO: Add insert logic here

                interfaceobj.InsertModel(collection);
                interfaceobj.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Contacts/Edit/5

        public ActionResult Edit(int id)
        {
            Contact c = interfaceobj.GetModelByID(id);
            return View(c);
        }

        //
        // POST: /Contacts/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, Contact collection)
        {
            try
            {
                // TODO: Add update logic here

                interfaceobj.UpdateModel(collection);
                interfaceobj.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Contacts/Delete/5

        public ActionResult Delete(int id)
        {
            Contact c = interfaceobj.GetModelByID(id);
            return View(c);
        }

        //
        // POST: /Contacts/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                interfaceobj.DeleteModel(id);
                interfaceobj.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
```

## Step 6

Create Controller class for BookTbl and controller name is "MyBooksController"

```
using MvcApplication11.Models;using MvcApplication11.Models.DAL;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcApplication11.Controllers{    public class MyBooksController : Controller    {        //        // GET: /MyBooks/        private _IAllRepository<BookTbl> interfaceobj;        public MyBooksController()        {            this.interfaceobj = new AllRepository<BookTbl>();        }        public ActionResult Index()        {            return View(from m in interfaceobj.GetModel() select m);        }        //        // GET: /MyBooks/Details/5        public ActionResult Details(int id)        {            BookTbl b = interfaceobj.GetModelByID(id);            return View(b);        }        //        // GET: /MyBooks/Create        public ActionResult Create()        {            return View();        }        //        // POST: /MyBooks/Create        [HttpPost]        public ActionResult Create(BookTbl collection)        {            try            {                // TODO: Add insert logic here                interfaceobj.InsertModel(collection);                interfaceobj.Save();                return RedirectToAction("Index");            }            catch            {                return View();            }        }        //        // GET: /MyBooks/Edit/5        public ActionResult Edit(int id)        {            BookTbl b = interfaceobj.GetModelByID(id);            return View(b);        }        //        // POST: /MyBooks/Edit/5        [HttpPost]        public ActionResult Edit(int id, BookTbl collection)        {            try            {                // TODO: Add update logic here                interfaceobj.UpdateModel(collection);                interfaceobj.Save();                return RedirectToAction("Index");            }            catch            {                return View();            }        }        //        // GET: /MyBooks/Delete/5        public ActionResult Delete(int id)        {            BookTbl b = interfaceobj.GetModelByID(id);            return View(b);        }        //        // POST: /MyBooks/Delete/5        [HttpPost]        public ActionResult Delete(int id, BookTbl collection)        {            try            {                // TODO: Add delete logic here                interfaceobj.DeleteModel(id);                interfaceobj.Save();                return RedirectToAction("Index");            }            catch            {                return View();            }        }    }}
```

## Step 7

Here add views according to their action like Insert Update and delete

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/f0846b5e-d52b-44cf-8af7-ade97cf8b150.png)\

1 - Views for BookTbl

For display, all record so create first "Index View"

```
@model IEnumerable<MvcApplication11.Models.BookTbl>
@{    Layout = null;}<!DOCTYPE html><html><head>
    <meta name="viewport" content="width=device-width" />    <title>Index</title></head><body>    <p>        @Html.ActionLink("Create New", "Create")    </p>    <table>        <tr>            <th>                @Html.DisplayNameFor(model => model.BookName)            </th>            <th>                @Html.DisplayNameFor(model => model.BookAuthor)            </th>            <th></th>        </tr>
    @foreach (var item in Model) {        <tr>            <td>                @Html.DisplayFor(modelItem => item.BookName)            </td>            <td>                @Html.DisplayFor(modelItem => item.BookAuthor)            </td>            <td>                @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ID })            </td>        </tr>    }
    </table>
</body>
</html>
```

Create

```
@model MvcApplication11.Models.BookTbl
@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>Create</title></head><body>    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    @using (Html.BeginForm()) {        @Html.ValidationSummary(true)        <fieldset>            <legend>BookTbl</legend>            <div class="editor-label">                @Html.LabelFor(model => model.BookName)            </div>            <div class="editor-field">                @Html.EditorFor(model => model.BookName)                @Html.ValidationMessageFor(model => model.BookName)            </div>            <div class="editor-label">                @Html.LabelFor(model => model.BookAuthor)            </div>            <div class="editor-field">                @Html.EditorFor(model => model.BookAuthor)                @Html.ValidationMessageFor(model => model.BookAuthor)            </div>            <p>
               <input type="submit" value="Create" />            </p>        </fieldset>    }    <div>        @Html.ActionLink("Back to List", "Index")    </div></body>
</html>
```

Update

```
@model MvcApplication11.Models.BookTbl@{
    Layout = null;}<!DOCTYPE html><html>
<head>    <meta name="viewport" content="width=device-width" />    <title>Edit</title></head><body>    <script src="~/Scripts/jquery-1.7.1.min.js"></script>    <script src="~/Scripts/jquery.validate.min.js"></script>    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>            <legend>BookTbl</legend>
            @Html.HiddenFor(model => model.ID)
            <div class="editor-label">
                @Html.LabelFor(model => model.BookName)            </div>            <div class="editor-field">                @Html.EditorFor(model => model.BookName)                @Html.ValidationMessageFor(model => model.BookName)            </div>
            <div class="editor-label">                @Html.LabelFor(model => model.BookAuthor)            </div>            <div class="editor-field">                @Html.EditorFor(model => model.BookAuthor)                @Html.ValidationMessageFor(model => model.BookAuthor)            </div>
            <p>
                <input type="submit" value="Save" />            </p>        </fieldset>    }    <div>        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>
```

Delete

```
@model MvcApplication11.Models.BookTbl@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />
 <title>Delete</title></head><body>    <h3>Are you sure you want to delete this?</h3>    <fieldset>        <legend>BookTbl</legend>
        <div class="display-label">             @Html.DisplayNameFor(model => model.BookName)        </div>        <div class="display-field">            @Html.DisplayFor(model => model.BookName)        </div>
        <div class="display-label">
             @Html.DisplayNameFor(model => model.BookAuthor)        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.BookAuthor)        </div>    </fieldset>    @using (Html.BeginForm()) {        <p>            <input type="submit" value="Delete" /> |
            @Html.ActionLink("Back to List", "Index")        </p>    }</body>
</html>
```

Details

```
@model MvcApplication11.Models.BookTbl@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>Details</title></head><body>    <fieldset>        <legend>BookTbl</legend>
        <div class="display-label">
             @Html.DisplayNameFor(model => model.BookName)
        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.BookName)        </div>
        <div class="display-label">             @Html.DisplayNameFor(model => model.BookAuthor)        </div>
        <div class="display-field">            @Html.DisplayFor(model => model.BookAuthor)        </div>
    </fieldset>    <p>        @Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |        @Html.ActionLink("Back to List", "Index")    </p></body></html>
```

And going on to create views for Contact table or contact [controller](https://www.mindstick.com/forum/2545/how-to-submit-form-to-controller-or-model-in-mvc).

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/048d43d8-0da8-4870-9858-abd782f26ef6.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/88f39ce2-afe3-4033-a8a6-6cf6fd511c4c.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/f815f513-16d9-4152-830f-5a491cf2bb38.png)

![Generic Repository Pattern in C#.](https://www.mindstick.com/mindstickarticle/095d03f1-fc98-4d48-bc14-da9c907347bd/images/ddda02ff-4bc4-4ff5-8a51-16ed457ed330.png)

\

\

Thank You.

---

Original Source: https://www.mindstick.com/articles/13124/generic-repository-pattern-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
