Generic Repository Pattern in C#

It’s a good practice to separate data access layer from business logic. Tight coupling of the database logic in the business logic make applications difficult to test and extend further. Direct access of the data in the business logic may cause problems such as:

  1. Difficulty completing Unit Test of the business logic
  2. Business logic cannot be tested without the dependencies of external systems like database
  3. Duplicate data access code throughout the business layer
  4. Difficulty to change the database provider (EntityFramework can be a solution).

Repository Pattern separates the data access logic and maps it to the entities in the business logic. It works with the domain entities and performs data access logic. In the Repository pattern, the domain entities, the data access logic and the business logic talk to each other using interfaces. It hides the details of data access from the business logic. In other words, business logic can access the data object without having knowledge of the underlying data access architecture. For example, in the Repository pattern, business logic is not aware whether the application is using LINQ to SQL or ADO.NET Entity Framework. In the future, underlying data sources or architecture can be changed without affecting the business logic.

There are various advantages of the Repository Pattern including:

  • Business logic can be tested without need for an external source
  • Database access logic can be tested separately
  • No duplication of code
  • Caching strategy for the datasource can be centralized
  • Domain driven development is easier
  • Centralizing the data access logic, so code maintainability is easier

Let’s consider the base IEntityBase.cs for each entity in the database.

Generic Repository Interface of the type IEntityBase can be created as follows. I have added basic CRUD operations as part of it. Keep in mind that if a particular repository requires additional operations, it can extend the generic repository interface.

We are going to work on the Employee table. To represent this, we have created an entity class Employee. Employee entity class should extend the IEntityBase class to work with the generic repository.

To create EmployeeRepository, create a class that will implement the generic repository interface IRepository<Employee>. I am performing CRUD operations using the Entity Framework. However, you may use any option like LINQ to SQL, ADO.NET etc.

The implemented generic repository can be used as follows: