Monthly Archives: April 2014

Image

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:

Difficulty completing Unit Test of the business logic

Business logic cannot be tested without the dependencies of external systems like database

Duplicate data access code throughout the business layer

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.

IEntityBase

C#

1

2

3

4

publicclassIEntityBase

{

publicstringId;

}

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.

Generic Repository

C#

1

2

3

4

5

6

7

8

publicinterfaceIBaseRepository<T>whereT:IEntityBase

{

IEnumerable<T>List{get;}

voidAdd(Tentity);

voidDelete(Tentity);

voidUpdate(Tentity);

TFindById(intId);

}

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.

C#

1

2

3

4

5

6

7

8

9

10

11

[Table("Employee")]

publicpartial classEmployee:IEntityBase

{

publicintId{get;set;}

[Required]

publicstringFirstName{get;set;}

[Required]

publicstringLastName{get;set;}

}

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.