In this article, we will discuss about the repository pattern and will create a simple example to get the basic working of this pattern.
To understand why we should be using this pattern, let’s take example of an MVC application, using the entity framework. As long as we are getting the correct results, we are not concerned with how the application code is structured, what are different layers defined, how they interact, how they pass the required data between them etc. and in most of the cases, we use the database context directly inside the controllers. This creates tight coupling between the controller and the data access layer, and if we closely look into this type of code, it violates the Single Responsibility Principle as well as Open close principle. Any change related to data-access layer can break the controller code. In such a case, our code structure have the following layers :
As seen from the above structure, layer 1 is directly using the database context and connects with the sql server. This is where the repository pattern can be implemented, to separate the layers. Our aim will be to separate the controller and the data access layer(database context) by using an intermediate layer i.e. repository layer, for communication between the two. So our code structure now changes to the following :
Example to use Repository pattern using C# :
To implement this pattern, we can either use the approach of having one-repository per model, which means, each entity of the database will have its own repository, or we can use a generic repository, which can be used by all the entities of the database.
For our example, we will be using the generic repository, with database first approach along with entity framework 5.0 and .Net framework 4.0. So let’s start with the example.
What is generic repository ?
A generic repository is a generic class, with basic CRUD methods in it (and of-course other methods can be added as per the need). This class and its member functions can be used for any entity of the database. This means, if we have entities
Orders, this single generic class can be used for both of them.
To start with, we will create a sample database with a table to store the
Customer data. We will be creating a simple form in mvc to add basic details in the table we created. Next, we will create a generic repository with our required operations to get all records, add/update/delete records. So our repository would look like the following.
TEntity is the generic type which can be any entity of the database i.e. it could be
Customer or it can be
Orders. All the operations will be applied on this
TEntity type only.
Next, our task will be to create a generic unit of work class. If you are not aware of the Unit of work in repository pattern, then I would suggest you to read this previous article to get an idea about this. Just to re-iterate about unit of work, it will act as the mediator between the mvc controller and the generic repository, to perform all database transactions in a single go (will discuss later in the article). This is because
SaveChanges will be called by the instance of unit of work class, only after it has performed operations for the entities involved. So our generic unit of work code will be like following:
Here, we have a method named
GetRepoInstance, which returns an instance of the type
TEntity will represents the entity for which we are going to perform the database operations. For example, if we are going to work with
Customer entity, it will return instance
GenericRepository<Customer> and if we are going to work with
Order entity, it will return
GenericRepository<Order>. Next we have the
SaveChanges method to commit all the database transactions in one go, by the current instance of unit of work we are using.
So we are done with setting up the unit of work class. Now we move in to the controller and will write the code for get/add/update/remove data. Let’s start with the listing of the records. We will discuss the
GetAllRecords repository method and on the same lines, rest of the methods will be called by the controller. To start with, we will create the
Customer repository instance, via use of the unit of work class. So we instantiate the unit of work class and call
GetRepoInstance method to get the instance of the
Customer repository. Now, when we call any method of the generic repository, it will call that method for the
Customer entity, as it holds the reference to
TEntity type at that time. This is because, when we initialized the generic repository, we created a
DbSet of the type
TEntity, in its constructor. So any type of CRUD operation is performed on the
DbSet. See the code below:
And, our controller method to fetch the records will look like the following:
That’s it. We are done with the code to get the records. Run the application and see the results. Similarly, we can write the code for the other operations of update/add/delete. Just instantiate the unit of work and get the instance for the entity repository. Call the methods and it’s all we have to do. Rest of our code will look like the following:
Why unit of work ?
Earlier in our article, we discussed a point about the preferred use of unit of work class. The advantage of using this class is the fact that when we are performing multiple operations in one single controller method, we will be committing all the changes in the database by calling the
SaveChanges only once and that is through the unit of work instance.
For example, in our above delete method, we might also want to delete the
Address related to that
Customer(assuming it is in a separate table). In that case, we find the associated address record using the
GetFirstOrDefault() method and call the delete operation for it. Finally, we call the
SaveChanges. In such a situation, if our first transaction fails, the other one will be also blocked, as the
SaveChanges is never executed and thus maintains the database consistency.
So this was a basic article to get started with the repository pattern. Hope you enjoyed reading it…!!!