Repository Design Pattern In ASP.NET MVC

Introduction


Why Design Pattern?

Traditionally, what do we do? We access our database directly, without using any middle layer or Data Access Layer (DAL).

Do you think this is a good approach? No, it's not! Here is why.

The tight coupling of the database logic in the business logic makes applications complex, tough to test, and tough to extend further. Direct access to the data in the business logic causes many problems like difficulty completing the Unit Test of the business logic, disability to test business logic without the dependencies of external systems like a database, and a duplicate data access code throughout the business layer. I hope we now know why we need a design pattern. There are many types of design patterns but in today’s article, we will discuss repository design patterns.

What is a Repository Design Pattern?

By definition, the Repository Design Pattern in C# mediates between the domain and the data mapping layers using a collection-like interface for accessing the domain objects. Repository Design Pattern separates the data access logic and maps it to the entities in the business logic. It works with the domain entities and performs data access logic. In the Repository pattern, the domain entities, the data access logic, and the business logic talk to each other using interfaces. It hides the details of data access from the business logic.

Advantages of Repository Design Pattern

  • Testing controllers becomes easy because the testing framework must not run against the database access code.
  • Repository Design Pattern separates the actual database, queries, and other data access logic from the rest of the application.
  • Business logic can access the data object without knowing the underlying data access architecture.
  • Business logic is unaware of whether the application uses LINQ to SQL or ADO.NET. In the future, underlying data sources or architecture can be changed without affecting the business logic.
  • The caching strategy for the data source can be centralized.
  • Centralizing the data access logic, so code maintainability is easier
  • Non-Generics Repository Design Pattern Source Code
  • Generics Repository Design Pattern Source Code

Implementation

Let’s do it practically and see how it is implemented. We will take a very basic example of implementation. I have attached the code file that you can download from the above link. I try to do it step by step and explain each step so that you can understand better. I will try to make it simple, clear, and understandable.

Step 1. Create Database

Let’s create a simple database (BasicDb) containing a single table with the name of Product_Table. The Backup and Script file is attached simply download it and restore it in SQL. You can choose any one file for restoration.

Step 2. Setup ASP.NET MVC Project

Create the Asp.Net MVC Project with the name of (Repository Design Pattern) screenshots are below.

Respository pattern

Select MVC

MVC

Step 3. Add Entity Framework

Create an Entity Framework to give the model name DataContext.

Models

Select Entity Framework Designer from the database.

Entity framework

Select Database

Select database

Change the name to (DataContext) it is optional you can keep it as it is.

Choose your data connection

Select Table

Select table

Step 4. Create DAL Folder

Create a Folder in the model folder with the name (DAL) where we will implement our repository.

Implement our repository

Step 5. Define Interface

Create an Interface Class (IProductRepository.cs)

Interface

Paste this Code to IProductRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repositiory_Pattern.Models.DAL
{
    interface IProductRepository
    {
        IEnumerable<Product_Table> GetProducts();
        Product_Table GetProductById(int ProductId);
        void InsertProduct(Product_Table product_);
        void UpdateProduct(Product_Table product_);
        void DeleteProduct(int ProductId);
        void SaveChanges();
    }
}

IProductRepository.cs

IProduct repository

Step 6. Implement Repository Class

Create a class in the DAL folder (ProductRepository.cs) This will be a child class and will implement all the methods of the (IProductRepository.cs) class. Paste this Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Repositiory_Pattern.Models.DAL
{
    public class ProductRepository : IProductRepository
    {
        private DataContext _dataContext;
        public ProductRepository(DataContext dataContext)
        {
            this._dataContext = dataContext;
        }
        public void DeleteProduct(int ProductId)
        {
            Product_Table product_ = _dataContext.Product_Table.Find(ProductId);
            _dataContext.Product_Table.Remove(product_);
        }
        public Product_Table GetProductById(int ProductId)
        {
            return _dataContext.Product_Table.Find(ProductId);
        }
        public IEnumerable<Product_Table> GetProducts()
        {
            return _dataContext.Product_Table.ToList();
        }
        public void InsertProduct(Product_Table product_)
        {
            _dataContext.Product_Table.Add(product_);
        }
        public void SaveChanges()
        {
            _dataContext.SaveChanges();
        }
        public void UpdateProduct(Product_Table product_)
        {
            _dataContext.Entry(product_).State = System.Data.Entity.EntityState.Modified;
        }
    }
}

ProductRepository.cs

Product repository

Step 7. Modify Home Controller

Now just go to our built-in Home Controller and paste this code.

using Repositiory_Pattern.Models;
using Repositiory_Pattern.Models.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Repositiory_Pattern.Controllers
{
    public class HomeController : Controller
    {
        private IProductRepository _productRepository;
        public HomeController()
        {
            this._productRepository = new ProductRepository(new DataContext());
        }
        public ActionResult Index()
        {
            return View(_productRepository.GetProducts());
        }
        public ActionResult Create()
        {
            return View(new Product_Table());
        }
        [HttpPost]
        public ActionResult Create(Product_Table product)
        {
            _productRepository.InsertProduct(product);
            _productRepository.SaveChanges();
            return RedirectToAction("Index");
        }
        public ActionResult Update(int Id)
        {
            return View(_productRepository.GetProductById(Id));
        }
        [HttpPost]
        public ActionResult Update(Product_Table product)
        {
            _productRepository.UpdateProduct(product);
            _productRepository.SaveChanges();
            return RedirectToAction("Index");
        }
        public ActionResult Delete(int Id)
        {
            _productRepository.DeleteProduct(Id);
            _productRepository.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}

HomeController.cs

Home controller

Step 8. Create Views

Now create the views Index, Create and Update. Just right-click on the method name.

Index.cshtml

Click on method name

Create.cshtml

Create

Update.cshtml

Update

Step 9. Adjust Index View

Open the Index view and change the action name Edit to Update and save.

Edit to update and save

Step 10. Run and Test

Now just run and see the result in the browser.

Run and see the result

Conclusion

In this project, we have performed CRUD operations using the Repository design pattern. We have created a single interface (IProductRepository.cs) and implemented all their methods in (ProductRepository.cs). Now if we have multiple entities or models then will we make an interface for each entity? No

We will not do this whereas we will make a single Generic (IModelRepository.cs) and (ModelRepository.cs) if we have multiple models we will use only a single interface and their single implementation class. The Generic Repository Project code I have attached so you can download it from the above-mentioned link. If you have any queries about the problem you face please comment below I will answer.

Don’t forget to like and share this article.


Similar Articles