Repository And Unity Of Work Pattern In MVC

Let’s first establish the purpose of the code.

For this article, the purpose of the code is how to structure your MVC code with repository and unity of work pattern, using Entity Framework.

What is repository and unity of work ?

The repository and unity of work pattern are used to create an abstraction layer between the data access layer and the business logic layer of an application.
 
For this article, I have the following two tables.

Book Table
  • BookID -- bigint -- Primary Key
  • BookName -- nvarchar(MAX)
  • Descrption -- nvarchar(MAX)
  • Price -- decimal(10, 2)
  • AutherID -- bigint -- Foregine Key With Auther Table 
Auther Table
  • AutherID -- bigint -- Primary Key
  • AutherName -- nvarchar(50)
The below script is used for generating the above tables.
  1. USE[DemoUnityRepository]  
  2. GO  
  3. /****** Object: Table [dbo].[Auther] Script Date: 11-01-2017 12:25:22 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE[dbo].[Auther](  
  9.     [AutherID][bigint] IDENTITY(1, 1) NOT NULL, [AutherName][nvarchar](50) NOT NULLCONSTRAINT[PK_Auther] PRIMARY KEY CLUSTERED(  
  10.         [AutherID] ASCWITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON[PRIMARY]) ON[PRIMARY]  
  11. GO  
  12. /****** Object: Table [dbo].[Book] Script Date: 11-01-2017 12:25:22 PM ******/  
  13. SET ANSI_NULLS ON  
  14. GO  
  15. SET QUOTED_IDENTIFIER ON  
  16. GO  
  17. CREATE TABLE[dbo].[Book](  
  18.     [BookID][bigint] IDENTITY(1, 1) NOT NULL, [BookName][nvarchar](maxNOT NULL, [Descrption][nvarchar](maxNOT NULL, [Price][decimal](10, 2) NOT NULL, [AutherID][bigintNOT NULL, [TagID][bigintNOT NULLCONSTRAINT[PK_Book] PRIMARY KEY CLUSTERED(  
  19.         [BookID] ASCWITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON[PRIMARY]) ON[PRIMARY] TEXTIMAGE_ON[PRIMARY]  
  20. GO  
  21. ALTER TABLE[dbo].[Book] WITH CHECK ADD CONSTRAINT[FK_Book_Auther] FOREIGN KEY([AutherID])  
  22. REFERENCES[dbo].[Auther]([AutherID])  
  23. GO  
  24. ALTER TABLE[dbo].[Book] CHECK CONSTRAINT[FK_Book_Auther]  
  25. GO  
  26. ALTER TABLE[dbo].[Book] WITH CHECK ADD CONSTRAINT[FK_Book_Tag] FOREIGN KEY([TagID])  
  27. REFERENCES[dbo].[Tag]([TagID])  
  28. GO  
  29. ALTER TABLE[dbo].[Book] CHECK CONSTRAINT[FK_Book_Tag]  
  30. GO 
Step 1 - Create an new MVC Application
  1. On the File menu, click New >> Project.
  2. In the "New Project" dialog box under Project types, expand Visual C# >> Web and in the Name box, type "DemoUnityRepository" followed by OK.
  3. Now, in the dialog box, click on the "MVC" under the ASP.NET 4.5.2 Templates. Then, click on "Change Authentication" which stays on center of the right side and finally, select "No Authentication" and click on OK.
  4. Add two folders IRepository and Repository.

    1. IRepository Folder -- for classes that contain interfaces.
    2. Repository Folder -- for classes that contain interfaces implementation.
Step 2 - Now, it's code time.
 
Add EDMX
  1. On the right side, you can find the Solution Explorer.
  2. In there, right click on "Models" Folder. Then, click on Add >> New Item.
  3. Now, click on the Visual C# and Select ADO.NET Entity Data Model, Name it "DBModel", and click on "OK".
  4. Select EF Designer from Database and click on "Next".
  5. Now, click on new connection, define "Server name", select authentication mode either Windows or SQL Server ( if SQL Server, then enter the username or password) and finally, select database "DemoUnityRepository" under "Connect to a Database". Click OK.
  6. Now, declare a name of connection string as "DBEntities" under "Save connection" setting in Web.config, then click on Next.
  7. Select version of Entity Framework. Select "Entity Framework 6.x" then click on "Next".
  8. Select "Table". Now, give the name space as "Models" under Model Namespace: and then click on OK.
  9. Now, Build your project by pressing CTRL + B for updating every entity perfectly.

STEP 3 - Implement Code

  1. Create an IRepository interface in IRepository Folder.

    IRepository interface contains all Generic method like Add | AddRange | Remove | Remove Range | Get | Get All
    1. public interface IRepository < TEntity > where TEntity: class {  
    2.     void Add(TEntity entity);  
    3.     void AddRange(IEnumerable < TEntity > entities);  
    4.     void Remove(TEntity entity);  
    5.     void RemoveRange(IEnumerable < TEntity > entities);  
    6.     TEntity Get(int id);  
    7.     IEnumerable < TEntity > GetAll();  
    8.     IEnumerable < TEntity > Find(Expression < Func < TEntity, bool >> predicate);  
    9. }  
    1. Add(TEntity entity) -- This method is used for inserting single row in single table.
    2. AddRange(IEnumerable<TEntity> entities) -- This method is used for inserting multiple rows in single table.
    3. Remove(TEntity entity) -- This method is used for removing single row from single table.
    4. RemoveRange(IEnumerable<TEntity> entities) -- This method is used for removing multiple row from single table.
    5. Get(int id) -- This method is used for retrieving single row according to id from table.
    6. GetAll() -- This method is used for retrieving all rows from table.
    7. Find(Expression<Func<TEntity, bool>> predicate) -- This method is used for retrieving all rows according to input condition from table.

  2. Now, implement IRepository interface. Create a Repository class in Repository Folder.
    1. public class Repository < TEntity > : IRepository < TEntity > where TEntity: class {  
    2.     //Here DBEntities is out context  
    3.     protected readonly DBEntities db;  
    4.     public Repository(DBEntities context) {  
    5.         db = context;  
    6.     }  
    7.     public void Add(TEntity entity) {  
    8.         db.Set < TEntity > ().Add(entity);  
    9.     }  
    10.     public void AddRange(IEnumerable < TEntity > entities) {  
    11.         db.Set < TEntity > ().AddRange(entities);  
    12.     }  
    13.     public void Remove(TEntity entity) {  
    14.         db.Set < TEntity > ().Remove(entity);  
    15.     }  
    16.     public void RemoveRange(IEnumerable < TEntity > entities) {  
    17.         db.Set < TEntity > ().RemoveRange(entities);  
    18.     }  
    19.     public TEntity Get(int id) {  
    20.         return db.Set < TEntity > ().Find(id);  
    21.     }  
    22.     public IEnumerable < TEntity > GetAll() {  
    23.         return db.Set < TEntity > ().ToList();  
    24.     }  
    25.     public IEnumerable < TEntity > Find(Expression < Func < TEntity, bool >> predicate) {  
    26.         return db.Set < TEntity > ().Where(predicate);  
    27.     }  
    28. }  
    Repository contains DbSet, So, it has Add, Get ,& Remove methods. While Unit of work contains DbContext, so it has Save Method.

  3. Create an IUnitOfWork interface in IRepository Folder and also inherit IDisposable interface in that class.
    1. public interface IUnitOfWork : IDisposable  
    2. {   
    3.    int SaveChanges();  
    4. }   
  4. Now, implement IUnitOfWork interface. Create a UnitOfWork class in Repository Folder.
    1. public class UnitOfWork: IUnitOfWork {  
    2.     private readonly DBEntities db;  
    3.     public UnitOfWork(DBEntities context) {  
    4.         db = context;  
    5.     }  
    6.     public int SaveChanges() {  
    7.         return db.SaveChanges();  
    8.     }  
    9.     public void Dispose() {  
    10.         db.Dispose();  
    11.     }  
    12. }  
    Why we use this pattern?

    The first reason is to "Minimize the duplicate query logic".

    How ? 

    For example, I have one situation that I want to display the  top five most expensive books of a particular author in my project, at multiple places. So, my LINQ query is like.
    1. var top5CostlyBooks = db.Books  
    2. .Where(s=>s.AutherID == id)   
    3. .OrderByDescending(s=>s.Price)  
    4. .Take(5);   
    Instead of this, if I create a repository for this situation, then I don't need to write this query again and again at different places but I need to call that repository.

    It's like this:
    1. var top5CostlyBooks = unitOfWork.Customs.GetTop5CostlyBook(); //"GetTop5CostlyBook" is implement in repository   
    The second reason is "to make a Business logic loosely typed".

    How?

    If we use Entity Framework directly, then our "Business Layer" is Tightly Coupled with "Data Access Layer". That means, if there are any changes or updates in EDMX, then we need to update our Business Logic.

    Now here, our "Business Layer" is loosely coupled with "Data Access Layer" because "Business Layer" is interacting with "Unity Of Work" & "Unity Of Work" is interacting with "Data Access Layer".

    Now, I have two situations.

    --> I want to get all the data from "Book" Table
    --> I want to get top 5 costly books Author wise from "Book" Table.

    In the 1st condition, I used Generic Repository and for the 2nd condition, I am going to create a new Custom Repository.

  5. Create an ICustomRepository interface in IRepository Folder and also inherit IRepository interface in that class.
    1. public interface ICustomRepository : IRepository<Book>  
    2. {   
    3.    IEnumerable<Book> GetTop5CostlyBookAutherWise(long AutherID);   
    4. }   
  6. Now, implement ICustomRepository interface. Create a CustomRepository class in Repository Folder.
    1. public class CustomRepository: Repository < Book > , ICustomRepository {  
    2.     public CustomRepository(DBEntities context): base(context) {}  
    3.     public DBEntities DBEntities {  
    4.         get {  
    5.             return db as DBEntities;  
    6.         }  
    7.     }  
    8.     public IEnumerable < Book > GetTop5CostlyBookAutherWise(long AutherID) {  
    9.         return DBEntities.Books.Where(s => s.AutherID == AutherID).OrderByDescending(s => s.Price).Take(5).ToList();  
    10.     }  
    11. }  
    Our all "Data Access Layer" code is cooked. Now, it's time for "Business Layer".

    Create the below Controller.
    1. public ActionResult Index(long BookID) {  
    2.     /* 
    3.     1 = Get All Books 
    4.     2 = Get Top 5 Costly Books Auther wise 
    5.     */  
    6.     List < Book > books = new List < Book > ();  
    7.     try {  
    8.         using(var unitOfWork = new UnitOfWork(new DBEntities())) {  
    9.             if (BookID == 1) {  
    10.                 //Called by GENERIC METHOD  
    11.                 books = unitOfWork.Customs.GetAll().ToList();  
    12.             } else if (BookID == 2) {  
    13.                 //Called by CUSTOM METHOD  
    14.                 books = unitOfWork.Customs.GetTop5CostlyBookAutherWise(1).ToList();  
    15.             }  
    16.         }  
    17.         return PartialView(books);  
    18.     } catch {  
    19.         throw;  
    20.     }  
    21. }  

Up Next
    Ebook Download
    View all
    Learn
    View all