Repository Pattern C#
Contents
- What Is Repository Pattern C# ?
- Why Repository Pattern C# ?
- Entity Framework Repository Pattern C#
- Generic Repository Pattern C#
- Unit Of Work Pattern C#
- Repository Pattern C# MVC
- Further Reading
- References
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:
And the implementation of the above interface with EF looks like this:
Usually, people argue on using repository pattern over EF as it restricts EF uses by returning IEnumnerable instead of IQueryable from the repository. You can learn more about it here.
Generic Repository Pattern C#
Creating a repository class for each entity type could result in a lot of repetitive code. Generic repository pattern is a way to minimize this repetition and have single base repository work for all type of data.
Let’s see the interface for the generic repository,
And the implementation of the above interface with EF looks like this:
The above generic repository defines core operations. You can extend this class and interface base on business requirement and can inherit in your custom repository.
Unit Of Work Pattern C#
Use of separate repository for a single transaction could result in partial updates. For example, suppose you have to update two different entity types as part of the same transaction. If each uses a separate database context instance, one might succeed and the other might fail, and one way to ensure that all repositories use the same database context (and thus coordinate all updates) is to use a unit of work class.
Unit of work pattern is easy to implement with the use of a generic repository. Let’s see an example,
Below is the code of how the implementation of above IUnitOfWork
will look like,
Unit of Work is the concept related to the effective implementation of the repository pattern, whether its non-generic repository pattern or generic repository pattern.
Unit of Work is referred to as a single transaction that involves multiple operations of insert/update/delete and so on. You can learn more about Unit of Work from this awesome post.
Repository Pattern C# MVC
Let’s see now how our controller code will look like after using repository pattern along with unit of work:
In the above code we directly initialized unitOfWork variable. Like this,
However to truly use the power of repository pattern and make the above controller testable we need to use IUnitOfWork
instead of UnitOfWork
for our unitOfWork
variable data type, and also we have to initialize it using Dependency Injection (DI) technique.
Assuming you’re starting with a new ASP.NET MVC 5 application, the easiest way to get StructureMap is using Nuget package StructureMap.MVC5.
After installing StructureMap, from solution explorer we can notice that Dependency Resolution folder has been added, also StructuremapMVC.cs file in App_Start folder.
The important file which is needed is the DefaultRegistry.cs. In Default Registry class, we are going configure StructureMap container. Let’s see how:
After configuring DefaultRegistry replace your CustomerController unitOfWork initialization code with the below code:
You can now start writing your unit tests for your controller classes from this base. Learn more about unit testing and how to use Moq library for mocking from this great article.
Further Reading
-
4 Common Mistakes with the Repository Pattern by Mosh Hamedani - People tend to make some common mistakes while creating a repository in C#. For example, repositories that return view models/DTOs. In this article you can learn more about this kind of mistakes and why you should avoid them.
-
Creating a Repository Pattern without an ORM by Jonathan Danylko - If you don’t feel like using an ORM, like Entity Framework, you can build your own data layer. In this post, Jonathan talk about a different way to pull data from a database using a strategy pattern.
-
Introducing the CachedRepository Pattern by Steve Smith - In this first part of a series on adding support for caching to the Repository Pattern, Steve show how to very simply control whether or not caching is performed on a per-repository basis through the use of an Inversion of Control Container.
References
- https://docs.microsoft.com/en-us/ef/ef6/
- https://softwareengineering.stackexchange.com/questions/192044/should-repositories-return-iqueryable
- https://stackoverflow.com/questions/33755499/entity-framework-repository-pattern-why-not-return-iqueryable
- https://programmingwithmosh.com/net/common-mistakes-with-the-repository-pattern/
- https://blogs.msdn.microsoft.com/diego/2010/10/05/self-tracking-entities-applychanges-and-duplicate-entities/
- https://stackoverflow.com/questions/10430880/managing-connections-with-generic-repository-pattern
- https://stackoverflow.com/questions/2025712/extract-sql-query-from-linq-expressions
- https://6figuredev.com/podcast/episode-029-generic-repository-repository-pattern/
- https://www.danylkoweb.com/Blog/creating-a-repository-pattern-without-an-orm-A9
- https://www.danylkoweb.com/Blog/enhancing-the-ado-repository-with-crud-functionality-CD
- https://ardalis.com/resolving-dependencies-in-asp-net-mvc-5-with-structuremap
- https://assignmentcore.com/csharp-homework/
Subscribe to Code with Shadman
Get the latest posts delivered right to your inbox