What Is Repository Pattern C# ?
A Repository in C# mediates between the domain and data mapping layers (like Entity Framework). It allows you to pull a record or number of records out of datasets, and then have those records to work on acting like an in-memory domain object collection, and you can also update or delete records within those data set, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes.
Repository pattern C# is a way to implement data access by encapsulating the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer.
Repository pattern C# also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
Repository pattern C# is mostly used where we need to modify the data before passing to the next stage.
here’s an awesome graph that illustrates the idea:
Why Repository Pattern C# ?
Increase testability: Repository systems are good for testing. One reason being that you can use Dependency Injection. Basically, you create an interface for your repository, and you reference the interface for it when you are making the object. Then you can later make a fake object (using moq for instance) which implements that interface. Using something like StructureMap you can then bind the proper type to that interface. Boom you’ve just taken a dependence out of the equation and replaced it with something testable.
Easily swapped out with various data stores without changing the API: For example, in one instance, you may need to retrieve data from the database, in other cases you may need to retrieve something from a third-party API, or perhaps there’s some other place from which you need to retrieve data. Regardless, the idea behind the repository pattern is that whatever sits behind it doesn’t matter so long as the API it provides works for the layer of the application calling into it.
Entity Framework Repository Pattern C#
Entity Framework (EF) itself implements Unit of work pattern and somewhat loosely implements Repository pattern. With EF you can retrieve a set of records from the database in POCO models. Also, EF keeps track of changes for you within these models and save these changes on single SaveChanges
method call.
Let’s see how to create a repository using EF, let say you have customer entity in your application, then this is how your customer repository interface will look like:
public interface ICustomerRepository
2 {
3 IEnumerable GetCustomers();
4 Customer GetCustomerByID(int customerId);
5 void InsertCustomer(Customer customer);
6 void DeleteCustomer(int customerId);
7 void UpdateCustomer(Customer customer);
8 void Save();
9 }
And the implementation of the above interface with EF looks like this: 1 public class CustomerRepository:ICustomerRepository
0 Comments