Understanding Repository and Unit of Work Pattern and Implementing Generic Repository in ASP.NET MVC using Entity Framework

In this article we will try understand the basics of Repository and Unit of Work Pattern and will also create small ASP.NET MVC sample application to implement a generic repository and unit of work class using entity framework.


I remember the .NET 1.1 days when we have to spend a considerable amount of time in writing the data access code for every application. Even though the nature of the code was almost the same, the difference in database schema made us write the separate data access layer for every application. With newer version of .NET frameworks, the possibility of being able to use ORMs(Object Relational Mapper) in our application saves us from writing lot of code that was earlier needed to be written for data access.

Since the ORMs make data access so straight forward that there is a possibility of having data access logic/predicates scattered all across the application. For instance, every controller can have the needed ObjectContext instance and can perform data access.

Repository and Unit of work pattern provides a clean way to access data using ORMs, keep all the data access logic in one central location and at the same time maintain the test-ablility of the application. Instead of talking about what a repository and unit of work is, let us try to understand these by implementing a simple ASP.NET MVC application.

Using the code

Let us first try to create a simple database on which we will be performing CRUD operations. We will define a simple Contacts tables in the database as:


Now with the database/table in created, we will use Entity framework and generate the ADO.NET entity data Model for these tables in our application. The generated entities will look like:


Performing Simple Data Access using MVC Scaffolding

Now we have the entity framework ready to be used in our application, Let us now Add a controller that will perform CRUD on the Contact table using Entity Framework.


And when we run this application, we will be able to perform the CRUD operation on the Contacts table.

Now there is nothing wrong from the code and functionality perspective in doing this. But there are two problems in this approach.

  1. The Data access code is scattered across the application(controllers) and this is a maintenance nightmare.
  2. The Action in the Controller is creating the Context inside itself. This makes this function non testable using dummy data and we can never be able to verify the results unless we use test data.

Note: If the second point is not clear then it is recommended to read about Test Driven Development using MVC. We cannot discuss it in this article otherwise the article will become digressing.

Creating a Repository

Now how can we solve the problem. We can solve the problem by moving all the data access code of entity framework in one place. So let us define a class that will contain all the data access logic for Contacts table.

But before creating this class, let us also think about the second problem for an instance. If we create a simple interface defining the contract for accessing the Contacts data and then implement this interface in our proposed class, we will have one benefit. We can then have another class implementing the same interface but playing around with the dummy data. Now as long as the controller is using the Interface our test projects can pass the dummy data class and our controller will not complain.

So let us first define the contract for accessing Contacts data.

And the implementation of this class will contain the actual logic to perform the CRUD operations on the Contacts table.

Now Let us create another Controller that will use this repository class perform the CRUD operations on Contacts table. lets call it Contacts2Controller

Now the benefit of this approach is that my ORM data access code is not scattered across the controllers. It is wrapped inside a repository class.

Having Multiple Repositories

Now imagine the scenario where we have multiple tables in the database. Then we need to create multiple repositories in order to map the domain model to the data model. Now having multiple repository classes poses on problem.

The problem is regarding the ObjectContext object. If we create multiple repositories, should they contain their ObjectContext separately? We know that using multiple instances of ObjectContext object simultaneously is a problem so should we really allow each repository to contain their own instances?

To solve this problem. Why to let each Repository class instance have its own instance of the ObjectContext. Why not create the instance of ObjectContext in some central location and then pass this instance to the repository classes whenever they are being instantiated. Now this new class will be called as UnitOfWork and this class will be responsible for creating the ObjectContext instance and handing over all the repository instances to the controllers.

Unit Of Work

So let us create a separate Repository to which will be used via UnitOfWork class and the ObjectContext will be passed to this class from outside.

Now this Repository class is taking the ObjectContext object from outside(whenever it is being created).

Now if we have to create multiple repositories, we can simply have all the repositories take the ObjectContext object at the time of construction. Now let us see how the UnitOfWork class creates the repository and passes it on to the Controller.

Now let us create one more Controller ContactsUowController that will use the unit of work class to perform the CRUD operations on the contact table.

Now the test-ablity of this controller is still maintained by having the combination of default and parametrized constructor. i.e. the test projects can pass on the UnitOfWork operating in dummy data rather than actual data. Also, the data access code is now centralized in one place with the possibility of having multiple repository classes being instantiated at the same time.

Generic Repository and Unit of Work

Now we have a Repository and UnitOfWork class in place. But the catch here is that if my database contain many tables then I will have to create those many repository classes and my UnitOfWork class need to have those many accessors properties for the repositories.

Wouldn’t it be better if we make our repository and UnitOfwork generic that we they will work with all the Model classes. So let us go ahead and implement a generic repository class.

UPDATE: Found a very interesting comment for this article which i think is worth putting in the article.

There are at least 2 overloads for ‘Where’ method:

When we are using

the query will use the ‘ IEnumerable’ version. In this case, the whole table records will be fetched from the database first and then the predicated will be applied to the final result. To prove it, just check out the produced SQL. It has no where clause.

To fix this issue, we need to change the ‘ Func’ to ‘ Expression Func'.

Now the ‘ IQueryable’ version of the ‘ Where’ method will be used.

Note: Thus perhaps using Expression Func better idea than using Func.

Now with this generic Repository, we will create a generic Unit of work class that will work with this generic repository. This unit of work class will check if the repository class for a particular type has been create already, same instance will be returned. else a new instance will be returned.

Now let us create one more Controller GenericContactsController that will use the GenericUnitOfWork class to perform the CRUD operations on the contact table.

And now we have a generic repository class with a unit of work in place.

Point of interest

In this article we saw what is Repository and Unit of work pattern. We have also seen a rudimentary implementation of Repository and unit of work pattern in an ASP.NET MVC application using entity framework. Then we saw how we can implement a generic repository class and get it to work with Unit of work class so that we don’t need to create multiple repository classes. I hope this has been informative.

Download sample code for this article: GenericRepoUowSample