Using the Repository Pattern with the Entity Framework

Image for post
Image for post
Image from Pexels

Through this article, we are going to see how to use the Repository Pattern with the Entity Framework in an ASP.NET MVC application.


The Repository Pattern, as well as the Unit of Work Pattern, allows to create an abstraction layer between the data access layer and the business logic layer of an application. The purpose of creating this layer is to isolate data access layer so that the changes we may operate cannot affect the business logic layer directly. Implementing these patterns is also helpful for automated unit testing or test-driven development.

The Repository Pattern

The Repository Pattern allows us to create an abstraction layer between the data access layer and the business logic layer of an application. So, this Data Access Pattern offers a more loosely coupled approach to data access. So, we are able to create the data access logic in a separate class, called a Repository, which has the responsibility of persisting the application’s business model.

The Unit of Work Pattern

The Unit of Work Pattern is a pattern that handles the transactions during data manipulation using the Repository Pattern. Unit of Work is referred to as a single transaction that involves multiple operations.

Setting up our project

First, we have to set up our project. So, let’s head to Visual Studio and choose “New Project > Visual C# > Web > ASP.NET We Application (.NET Framework)”. Name our application “GameApplication”.

Now, let’s install the Entity Framework and enable Migrations:

Installing Entity Framework and enabling migrations

Enable Routes attributes:

Adding Attributes Routes in App_Start/RouteConfig.cs file

We can now create our first Model, that we are going to name “Game”, like so:

Models/Game.cs file

We now have to create a “DAL” folder at the root of our application where we are going to create a “GameContext” file.

DAL/GameContext.cs file

Now, in the “Migrations/Configuration.cs” file, let’s place the following code:

Migrations/Configuration.cs file

We then have to make little changes in our “Web.config” file:

Web.config file edited

Now, we are ready to create our first Controller. Let’s choose the “MVC 5 Controller with views, using Entity Framework” option and name it “GameController”. We can enter “Game” as the Model class and “GameContext” for the database Context. After a few seconds, we can see that a Controller with some code in it and a bunch of Views have been created for us.

Now, if we run our application and go to “localhost:RANDOM_PORT/game”, we should see something interesting.

Generic Repository

There are many ways to implement the Repository Patterns. We could create a Repository Class for each entity type, but it results in a lot of redundant code or in partial updates. So, to avoid this, we are going to create a Generic Repository.

First, let’s create a file named “GenericRepository.cs” in our “DAL” folder and fill it like so:

DAL/GenericRepository.cs file

As we can see, first, we declare two class variables: one for the context and one for the entity set that the Repository is instantiated for. The constructor accepts a database context instance and initializes the entity set variable.

If we just overview the class, we can notice that the code declares a typical set of “CRUD” methods.

The signature of the “Get()” method can seem impressive. The first two arguments are lambda expressions. “Expression<Func<TEntity, bool>> filter” means that a lambda expression, based on “TEntity”, will be provided and it will return a Boolean value. “Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy” also means that a lambda expression will be provided. The input of this expression is an “IQueryable” object and it will return an ordered version of that object. Finally, the third argument is a string that allows us to provide a comma-delimited list of navigation properties for eager loading. In the body of this method, we can see that, first, the filter expression is applied if there is one. Secondly, the eager-loading expression is performed. Finally, the order expression is applied if there is one.

Come next two methods, one to get an Entity by its ID, then a method that handles insertion. We then have two “Delete()” methods that manage the deletion. Finally, we find the “Update()” method.

Unit of Work

As we said, the role of the Unit of Work class is to make sure that, when we use multiple Repositories, they share a single database Context. So, when a Unit of Work is complete, the “SaveChanges()” method is called on the instance corresponding to the current Context. We are then assured that all related changes will be coordinated.

Let’s create a file named “UnitOfWork.cs” in our “DAL” folder and fill it like so:

DAL/UnitOfWork.cs file

If we look at the code, we can see that the class implements the “IDisposable” interface. The main purpose of this interface is to release unmanaged resources. A managed resource means “managed memory” that is managed by the garbage collector. When we no longer have any references to a managed object, which uses managed memory, the garbage collector will release that memory for us. So, unmanaged resources are everything that the garbage collector does not know about (open files, open network connections, etc.). So, using the “Dispose()” method of this interface allows us to release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

We also have a class variable for the database Context and another for the Repository we are going to use. If there were more Repositories, we would have to add variables representing each of them. We then perform a check to see if our Repository already exists. If not, we instantiate it using the Context instance.

The “Save()” method calls the “SaveChanges()” on the Context.

Changing the Controller

Now, let’s go back to our “GameController” and change it like so:

Controllers/GameController.cs file edited

Here, we add a class variable for the “UnitOfWork”. One improvement we could do here is to use the constructor instead or to use Dependency Injection. The main change is that every reference to the database Context is replaced by a reference to the appropriate Repository, using “UnitOfWork” properties to access the Repository.

If we run our application again, we see that it looks and works the same as before.


Through this article, we defined the Repository and the Unit of Work patterns. We saw which concept they encapsulate and how we can use them in our application.

One last word

If you like this article, you can consider supporting and helping me on Patreon! It would be awesome! Otherwise, you can find my other posts on Medium and Tumblr. You will also know more about myself on my personal website. Until next time, happy headache!

Written by

WebDeveloper / Writer / Musician / /

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store