In this post, I am explaining generic repository pattern using EF7. The Repository Pattern is a common construct to avoid duplication of data access logic throughout our application. The purpose of the repository is to hide the details of accessing the data. We can easily query the repository for data objects, without having to know how to provide things like a connection string. The Repository pattern adds a layer between the data and domain layers of an application. It also makes the data access parts of an application better testable.
Here is the initial version of repository interface.
It is specific to Employee class, respository contains CRUD operations. And here is the implementation of EmployeeRepository class with DbContext.
And here is the Employee context object.
There are two problems with current EmployeeRepository implementation. First one it is using one model class, Employee, if you have multiple model classes, you need to duplicate lot of code. Second is it is not testable. The first problem you can fix by make it generic. And the second problem you can resolve by injecting the context object. Here is the generic repository interface.
The IEntity interface contains only one property, Id.
And here is the implementation of GenericRepository class.
In this implementation, one more problem exists, in the DbContext implementation, you need the reference of Employee model. You can make it DbContext also generic using Reflection.
In OnModelCreating method, all the types which implements IEntity interface are added to the DbContext using Entity() method. This method is invoked dynamically using reflection. In ASP.NET 5 you can inject the repository and the context using inbuilt dependency injection feature.
And here is the unit tests for create
Happy Programming :)
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.
Did you like this article? Share it with your friends