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 in 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 pattern.
 

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 need not run against the actual 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 having knowledge of the underlying data access architecture.
  • Business logic is not aware of whether the application is using LINQ to SQL or ADO.NET. In the future, underlying data sources or architecture can be changed without affecting the business logic.
  • 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 implements. 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 explained each step so that you can understand better. I full try to make it simple, clear and understandable.
 
Step 1
 
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
 
Create the Asp.Net MVC Project with the name of (Repository Design Pattern) screenshots are below.
 
Repository Design Pattern In ASP.NET MVC
 
Select MVC
 
Repository Design Pattern In ASP.NET MVC
 
Step 3
 
Create an Entity Framework to give the model name DataContext.
 
Repository Design Pattern In ASP.NET MVC
 
Select Entity framework designer from the database.
 
Repository Design Pattern In ASP.NET MVC
 
Select Database
 
Repository Design Pattern In ASP.NET MVC
 
Change name to (DataContext) it is optional you can keep as it is,
 
Repository Design Pattern In ASP.NET MVC
 
Select Table
 
Repository Design Pattern In ASP.NET MVC
 
Step 4
 
Create a Folder in the model folder with the name (DAL) where we will implement our repository.
 
Repository Design Pattern In ASP.NET MVC
 
Step 5
 
Create an Interface Class (IProductRepository.cs)
 
Repository Design Pattern In ASP.NET MVC

Paste this Code to IProductRepository.cs,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace Repositiory_Pattern.Models.DAL  
  8. {  
  9.     interface IProductRepository  
  10.     {  
  11.         IEnumerable<Product_Table> GetProducts();  
  12.         Product_Table GetProductById(int ProductId);  
  13.         void InsertProduct(Product_Table product_);  
  14.         void UpdateProduct(Product_Table product_);  
  15.         void DeleteProduct(int ProductId);  
  16.         void SaveChanges();  
  17.     }  

IProductRepository.cs

Repository Design Pattern In ASP.NET MVC
 
Step 6
 
Create a class in the DAL folder (ProductRepository.cs) This will be child class and will implement all the methods of (IProductRepository.cs) class. Paste this Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace Repositiory_Pattern.Models.DAL  
  7. {  
  8.     public class ProductRepository:IProductRepository  
  9.     {  
  10.         private DataContext _dataContext;  
  11.         public ProductRepository(DataContext dataContext)  
  12.         {  
  13.             this._dataContext = dataContext;  
  14.         }  
  15.         public void DeleteProduct(int ProductId)  
  16.         {  
  17.             Product_Table product_ = _dataContext.Product_Table.Find(ProductId);  
  18.             _dataContext.Product_Table.Remove(product_);  
  19.         }  
  20.         public Product_Table GetProductById(int ProductId)  
  21.         {  
  22.             return _dataContext.Product_Table.Find(ProductId);  
  23.         }  
  24.         public IEnumerable<Product_Table> GetProducts()  
  25.         {  
  26.             return _dataContext.Product_Table.ToList();  
  27.         }  
  28.         public void InsertProduct(Product_Table product_)  
  29.         {  
  30.             _dataContext.Product_Table.Add(product_);  
  31.         }  
  32.         public void SaveChanges()  
  33.         {  
  34.             _dataContext.SaveChanges();  
  35.         }  
  36.         public void UpdateProduct(Product_Table product_)  
  37.         {  
  38.          _dataContext.Entry(product_).State = System.Data.Entity.EntityState.Modified;  
  39.         }  
  40.     }  

ProductRepository.cs
 
Repository Design Pattern In ASP.NET MVC
 
Step 7
 
Now just go to our built-in Home Controller and paste this code.
  1. using Repositiory_Pattern.Models;  
  2. using Repositiory_Pattern.Models.DAL;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace Repositiory_Pattern.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         private IProductRepository _productRepository;  
  14.         public HomeController()  
  15.         {  
  16.             this._productRepository = new ProductRepository(new DataContext());  
  17.         }  
  18.         public ActionResult Index()  
  19.         {  
  20.             return View(_productRepository.GetProducts());  
  21.         }       
  22.         public ActionResult Create()  
  23.         {  
  24.             return View(new Product_Table());  
  25.         }  
  26.         [HttpPost]  
  27.         public ActionResult Create(Product_Table product)  
  28.         {  
  29.             _productRepository.InsertProduct(product);  
  30.             _productRepository.SaveChanges();  
  31.             return RedirectToAction("Index");  
  32.         }              
  33.         public ActionResult Update(int Id)  
  34.         {  
  35.             return View(_productRepository.GetProductById(Id));  
  36.         }  
  37.         [HttpPost]  
  38.         public ActionResult Update(Product_Table product)  
  39.         {  
  40.             _productRepository.UpdateProduct(product);  
  41.             _productRepository.SaveChanges();  
  42.             return RedirectToAction("Index");  
  43.         }              
  44.         public ActionResult Delete(int Id)  
  45.         {  
  46.             _productRepository.DeleteProduct(Id);  
  47.             _productRepository.SaveChanges();  
  48.             return RedirectToAction("Index");  
  49.         }  
  50.     }  

HomeController.cs
 
Repository Design Pattern In ASP.NET MVC
 
Step 8
 
Now create the views Index, Create and Update. Just right click on the method name.
 
Index.cshtml
 
Repository Design Pattern In ASP.NET MVC
 
Create.cshtml

Repository Design Pattern In ASP.NET MVC
 
Update.cshtml
 
Repository Design Pattern In ASP.NET MVC
 
Step 9
 
Open the Index view and change the action name Edit to Update and save.
 
Repository Design Pattern In ASP.NET MVC
 
Step 10
 
Now just run and see the result in the browser.
 
Repository Design Pattern In ASP.NET MVC
 

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 mention 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