18 Jan 2019
Repository Patterns

Repository Patterns

Reading and writing to the database is required by almost any system. Hence having an efficient method for communicating with the database is vital. Accessing the data in business logic can result in duplicated code, errors, weak typing, and inability to easily test the business logic in isolation. This is where repository patterns are very helpful.

Repository patterns maximize the amount of code that can be tested, allow for easy access to the data source, and improve the code’s maintainability and readability.

Repository pattern advantages are:

• Business logic can be unit tested without data access logic
• The database access code can be reused
• Database access code is centrally managed, making it easier to implement any database access policies.

A repository is a class defined for an entity, with all the operations possible on that specific entity.

For example, an entity Student will have operations like:

• void Insert(Student obj)
• void Update(Student obj)
• Student SelectById(string id)

An entity like Faculty will have operations like:

• void Insert(Faculty obj)
• void Update(Faculty obj)
• Faculty SelectById(string id)

This is an example for one repository per entity (non-generic). In this case, the two entities Student and Faculty, each have its own repository.

To further improve the efficiency, where there may be many entities with similar operations, we use Generic repositories. A generic repository is one that can be used for all entities. In the Generic repository interface, the operations will be defined using T instead of the entity.
For example, the operations will be:

• void Insert(T obj)
• void Update(T obj)
• T SelectById(string id)

This method can now be used for creating new students or creating new faculties since it is not entity-specific.
Benefits of Generic Repository Pattern:

• It reduces redundancy of code.
• It creates the possibility of less error.
• Easy to maintain the centralized data access logic.

Melody Fernandes

Post Comments

* marked fields are mandatory.