Generic Repository Pattern in MVC3 Application With Entity Framework: Part 6

Introduction

 
Creating a Generic Repository Pattern in MVC3 Application with Entity Framework is the last topic that we are about to cover in our journey of Learning MVC.
 
This article will focus on the Unit Of Work Pattern and Repository Pattern, and shows how to perform CRUD operations in an MVC application when there is the possibility of creating more than one repository class. To overcome this possibility and overhead, we make a Generic Repository class for all other repositories and implement a Unit of Work pattern to provide abstraction.
 
Our roadmap towards Learning MVC
 
Just as a reminder, our full roadmap towards learning MVC is:
Prerequisites
 
There are a few prerequisites before we starting with the article; they are:
  1. We have a running sample application that we created in the fifth part of the article series.
  2. We have the EntityFramework 4.1 package or DLL in our local system.
  3. We understand how a MVC application is created (follow the second part of the series).

Why Generic Repository

 
image1.gif 
 
We have already discussed what the Repository Pattern is and why we need the Repository Pattern in our last article. We created a User Repository for performing CRUD operations, but think of the scenario where we need 10 such repositories.
 
image2.gif 
 
Are we going to create these classes? That is not good, it results in a lot of redundant code. So to overcome that we'll create a Generic Repository class that will be called by a property to create a new repository, thus we do not get many results in many classes and also avoid redundant code. Moreover we save a lot of time that could be wasted creating those classes.
 

Unit of Work Pattern

 
According to Martin Fowler, the Unit of Work Pattern "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.".
 
From MSDN:
"The Unit of Work pattern isn't necessarily something that you will explicitly build yourself, but the pattern shows up in nearly every persistence tool. The ITransaction interface in NHibernate, the DataContext class in LINQ to SQL, and the ObjectContext class in the Entity Framework are all examples of a Unit of Work. For that matter, the venerable DataSet can be used as a Unit of Work.

Other times, you may want to write your own application-specific Unit of Work interface or class that wraps the inner Unit of Work from your persistence tool. You may do this for a number of reasons. You might want to add application-specific logging, tracing, or error handling to transaction management. Perhaps you want to encapsulate the specifics of your persistence tooling from the rest of the application. You might want this extra encapsulation to make it easier to swap out persistence technologies later. Or you might want to promote testability in your system. Many of the built-in Unit of Work implementations from common persistence tools are difficult to deal with in automated unit testing scenarios.

The Unit of Work class can have methods to mark entities as modified, newly created, or deleted. The Unit of Work will also have methods to commit or roll back all of the changes as well.

The responsibilities of the Unit of Work are to:
  • Manage transactions.
  • Order the database inserts, deletes, and updates.
  • Prevent duplicate updates. Inside a single usage of a Unit of Work object, various parts of the code may mark the same Invoice object as changed, but the Unit of Work class will only issue a single UPDATE command to the database. 
The value of using a Unit of Work pattern is to free the rest of our code from these concerns so that you can otherwise concentrate on business logic."

Why use Unit of Work?

 
Again Martin Fowler says,"When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data won't be written back into the database. Similarly you need to insert new objects you create and remove any objects you delete.
 
You can change the database with each change to your object model, but this can lead to many very small database calls, which ends up being very slow. Furthermore it requires you to have a transaction open for the entire interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you've read so you can avoid inconsistent reads.
 
image3.gif 
 
A Unit of Work keeps track and takes responsibility of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work."
 
You see I don't need to concentrate much on theory, we already have great definitions, all we needed is to stack them in a correct format.
 
Using the Unit of Work
 
One of the best ways to use the Unit of Work pattern is to allow disparate classes and services to take part in a single logical transaction. The key point here is that you want the disparate classes and services to remain ignorant of each other while being able to enlist in a single transaction. Traditionally, you've been able to do this by using transaction coordinators like MTS/COM+ or the newer System.Transactions namespace. Personally, I prefer using the Unit of Work pattern to allow unrelated classes and services to take part in a logical transaction because I think it makes the code more explicit, easier to understand, and simpler to unit test (also from MSDN).
 

Creating Generic Repository

 
image4.gif 
 
Cut the Redundancy
 
Step 1 : Open up our existing MVC3 application created in Part 5 in Visual Studio.
 
Step 2 : Right-click the Learning MVC project folder and create a folder named GenericRepository and add a class named GenericRepository.cs to that folder.
 
The code of the GenericRepository.cs class is as follows:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Linq.Expressions;   
  7. namespace LearningMVC.GenericRepository  
  8. {  
  9.     public class GenericRepository<TEntity> where TEntity : class  
  10.     {  
  11.         internal MVCEntities context;  
  12.         internal DbSet<TEntity> dbSet;   
  13.         public GenericRepository(MVCEntities context)  
  14.         {  
  15.             this.context = context;  
  16.             this.dbSet = context.Set<TEntity>();  
  17.         }   
  18.         public virtual IEnumerable<TEntity> Get()  
  19.         {  
  20.             IQueryable<TEntity> query = dbSet;  
  21.             return query.ToList();  
  22.         }   
  23.         public virtual TEntity GetByID(object id)  
  24.         {  
  25.             return dbSet.Find(id);  
  26.         }   
  27.         public virtual void Insert(TEntity entity)  
  28.         {  
  29.             dbSet.Add(entity);  
  30.         }   
  31.         public virtual void Delete(object id)  
  32.         {  
  33.             TEntity entityToDelete = dbSet.Find(id);  
  34.             Delete(entityToDelete);  
  35.         }   
  36.         public virtual void Delete(TEntity entityToDelete)  
  37.         {  
  38.             if (context.Entry(entityToDelete).State == EntityState.Detached)  
  39.             {  
  40.                 dbSet.Attach(entityToDelete);  
  41.             }  
  42.             dbSet.Remove(entityToDelete);  
  43.         }   
  44.         public virtual void Update(TEntity entityToUpdate)  
  45.         {  
  46.             dbSet.Attach(entityToUpdate);  
  47.             context.Entry(entityToUpdate).State = EntityState.Modified;  
  48.         }  
  49.     }  
  50. }
We can see, we have created the generic methods and the class as well is generic, when instantiating this class we can any model on which the class will work as a repository and serve the purpose.
 
TEntity is any model/domain/entity class.
 
MVCEntities is our DBContext as discussed in earlier parts.
 
Step 3 : Implementing UnitOfWork: Create a folder named UnitOfWork under the LearningMVC project, and add a class UnitOfWork.cs to that folder.
 
The code of the class is as follows:
  1. using System;  
  2. using LearningMVC.GenericRepository;   
  3. namespace LearningMVC.UnitOfWork  
  4. {  
  5.     public class UnitOfWork : IDisposable  
  6.     {  
  7.         private MVCEntities context = new MVCEntities();  
  8.         private GenericRepository<User> userRepository;   
  9.         public GenericRepository<User> UserRepository  
  10.         {  
  11.             get  
  12.             {  
  13.                 if (this.userRepository == null)  
  14.                     this.userRepository = new GenericRepository<User>(context);  
  15.                 return userRepository;  
  16.             }  
  17.         }   
  18.         public void Save()  
  19.         {  
  20.             context.SaveChanges();  
  21.         }   
  22.         private bool disposed = false;   
  23.         protected virtual void Dispose(bool disposing)  
  24.         {  
  25.             if (!this.disposed)  
  26.             {  
  27.                 if (disposing)  
  28.                 {  
  29.                     context.Dispose();  
  30.                 }  
  31.             }  
  32.             this.disposed = true;  
  33.         }   
  34.         public void Dispose()  
  35.         {  
  36.             Dispose(true);  
  37.             GC.SuppressFinalize(this);  
  38.         }  
  39.     }  
  40. }
We see the class implements the IDisposable interface for objects of this class to be disposed.
 
We create an object of DBContext in this class, note that earlier it was used to be ed in the Repository class from a controller.
 
Now it's time to create our User Repository. We see in the code itself that, simply a variable named userRepository is declared as private GenericRepository<User> userRepository; of type GenericRepository serving User entity to the TEntity template.
 
Then a property is created for the same userRepository variable in a very simplified manner as in the following:
  1. public GenericRepository<User> UserRepository  
  2. {  
  3.      get  
  4.      {  
  5.          if (this.userRepository == null)  
  6.              this.userRepository = new GenericRepository<User>(context);  
  7.          return userRepository;  
  8.      }  
  9. }
In other words, merely 6-7 lines of code. Guess what? Our UserRepository is created.
 
image5.gif 
(taken from google)
 
You see, it was as simple as that, you can create as many repositories as you want by just creating simple properties, and there is no need to create separate classes. And now you can complete the rest of the story by yourself. Confused????,Yes its DBOperations, let's do it.
 
Step 4 : In MyController, declare a variable unitOfWork as:
  1. private UnitOfWork.UnitOfWork unitOfWork = new UnitOfWork.UnitOfWork();
Now this unitOfWork instance of the UnitOfWork class holds all the repository properties. If we press "." after it then it will show the repositories.So we can choose any of the repositories created and perform CRUD operations on them. For example our Index action:
  1. public ActionResult Index()  
  2. {  
  3.       var userList = from user in unitOfWork.UserRepository.Get() select user;  
  4.       var users = new List<LearningMVC.Models.UserList>();  
  5.       if (userList.Any())  
  6.       {  
  7.             foreach (var user in userList)  
  8.             {  
  9.                   users.Add(new LearningMVC.Models.UserList() { UserId = user.UserId, Address = user.Address, Company = user.Company, FirstName = user.FirstName, LastName =  
  10. user.LastName, Designation = user.Designation, EMail = user.EMail, PhoneNo = user.PhoneNo });  
  11.             }  
  12.        }  
  13.        ViewBag.FirstName = "My First Name";  
  14.        ViewData["FirstName"] = "My First Name";  
  15.        if(TempData.Any())  
  16.        {  
  17.             var tempData = TempData["TempData Name"];  
  18.        }  
  19.        return View(users);  
  20. }
Here,
 
unitOfWork.UserRepository - Accessing UserRepository.
unitOfWork.UserRepository.Get() - Accessing Generic Get() method to get all users.
 
Earlier we had the MyController constructor like:
  1. public MyController()  
  2. {  
  3.      this.userRepository = new UserRepository(new MVCEntities());  
  4. }
We now do not need to write that constructor, in fact you can remove the UserRepository class and interface we created in the fifth part of Learning MVC.
 
I hope you can write the actions for the rest of the CRUD operations as well.
 
Details
  1. public ActionResult Details(int id)  
  2. {  
  3.        var userDetails = unitOfWork.UserRepository.GetByID(id);  
  4.        var user = new LearningMVC.Models.UserList();  
  5.        if (userDetails != null)  
  6.        {  
  7.              user.UserId = userDetails.UserId;  
  8.              user.FirstName = userDetails.FirstName;  
  9.              user.LastName = userDetails.LastName;  
  10.              user.Address = userDetails.Address;  
  11.              user.PhoneNo = userDetails.PhoneNo;  
  12.              user.EMail = userDetails.EMail;  
  13.              user.Company = userDetails.Company;  
  14.              user.Designation = userDetails.Designation;  
  15.        }  
  16.        return View(user);  
Create:
  1. [HttpPost]  
  2. public ActionResult Create(LearningMVC.Models.UserList userDetails)  
  3. {  
  4.      try  
  5.      {  
  6.           var user = new User();  
  7.           if (userDetails != null)  
  8.           {  
  9.                 user.UserId = userDetails.UserId;  
  10.                 user.FirstName = userDetails.FirstName;  
  11.                 user.LastName = userDetails.LastName;  
  12.                 user.Address = userDetails.Address;  
  13.                 user.PhoneNo = userDetails.PhoneNo;  
  14.                 user.EMail = userDetails.EMail;  
  15.                 user.Company = userDetails.Company;  
  16.                 user.Designation = userDetails.Designation;  
  17.           }  
  18.           unitOfWork.UserRepository.Insert(user);  
  19.           unitOfWork.Save();  
  20.           return RedirectToAction("Index");  
  21.      }  
  22.      catch  
  23.      {  
  24.           return View();  
  25.      }  
  26. }
Edit:
  1. public ActionResult Edit(int id)  
  2. {  
  3.      var userDetails = unitOfWork.UserRepository.GetByID(id);  
  4.      var user = new LearningMVC.Models.UserList();  
  5.      if (userDetails != null)  
  6.      {  
  7.           user.UserId = userDetails.UserId;  
  8.           user.FirstName = userDetails.FirstName;  
  9.           user.LastName = userDetails.LastName;  
  10.           user.Address = userDetails.Address;  
  11.           user.PhoneNo = userDetails.PhoneNo;  
  12.           user.EMail = userDetails.EMail;  
  13.           user.Company = userDetails.Company;  
  14.           user.Designation = userDetails.Designation;  
  15.      }  
  16.      return View(user);  
  17. }   
  18. [HttpPost]  
  19. public ActionResult Edit(int id, User userDetails)  
  20. {  
  21.      TempData["TempData Name"] = "Akhil";  
  22.      try  
  23.      {  
  24.            var user = unitOfWork.UserRepository.GetByID(id);  
  25.            user.FirstName = userDetails.FirstName;  
  26.            user.LastName = userDetails.LastName;  
  27.            user.Address = userDetails.Address;  
  28.            user.PhoneNo = userDetails.PhoneNo;  
  29.            user.EMail = userDetails.EMail;  
  30.            user.Company = userDetails.Company;  
  31.            user.Designation = userDetails.Designation;  
  32.            unitOfWork.UserRepository.Update(user);  
  33.            unitOfWork.Save();  
  34.            return RedirectToAction("Index");  
  35.      }  
  36. }
Delete:
  1. public ActionResult Delete(int id)  
  2. {  
  3.      var user = new LearningMVC.Models.UserList();  
  4.      var userDetails = unitOfWork.UserRepository.GetByID(id);   
  5.      if (userDetails != null)  
  6.      {  
  7.           user.FirstName = userDetails.FirstName;  
  8.           user.LastName = userDetails.LastName;  
  9.           user.Address = userDetails.Address;  
  10.           user.PhoneNo = userDetails.PhoneNo;  
  11.           user.EMail = userDetails.EMail;  
  12.           user.Company = userDetails.Company;  
  13.           user.Designation = userDetails.Designation;  
  14.      }  
  15.     return View(user);  
  16. }   
  17. [HttpPost]  
  18. public ActionResult Delete(int id, LearningMVC.Models.UserList userDetails)  
  19. {  
  20.      try  
  21.      {  
  22.           var user = unitOfWork.UserRepository.GetByID(id);   
  23.           if (user != null)  
  24.           {  
  25.                unitOfWork.UserRepository.Delete(id);  
  26.                unitOfWork.Save();  
  27.            }   
  28.            return RedirectToAction("Index");  
  29.       }  
  30.      catch  
  31.      {  
  32.            return View();  
  33.       }  
  34. }
Note: Images are taken from Google images.
 

Conclusion

 
We now know how to make generic repositories too, and perform CRUD operations using it.
 
We have also learned the UnitOfWork pattern in detail. Now you are qualified and confident enough to apply these concepts in your enterprise applications. This was the last part of this MVC series, let me know if you wish to discuss any topic in particular or we can also start another series as well.
 
Read more:
Other Series
 
My other series of articles:
For more informative articles visit my Blog.
 
Happy Coding. 


Similar Articles