Repository Pattern with C# and Entity Framework, Done Right

By: Programming with Mosh

3088   49   223509

Uploaded on 10/15/2015

There are many tutorials about the repository pattern and many of them are conflicting. If you've been confused about the proper way to implement the repository and unit of work patterns with Entity Framework, this video is for you.

00:00 What is the Repository Pattern?
00:47 Benefits of the Repository Pattern
03:50 Repository in a Nutshell
04:47 What is the Unit of Work Pattern?
05:00 Does Entity Framework Really Implement Repository and Unit of Work Patterns?
09:31 Clean Architecture
11:43 Implementing the Repository Pattern
14:09 Implementing the Unit of Work Pattern
15:09 Repository and Unit of Work Patterns in Code
22:49 Example of Repository and Unit of Work Patterns

Download the source code for this video here:

This video is part of my in-depth Entity Framework course. If you're interested, you can get the course with a discount here:

And here are some YouTube videos of mine you might be interested in:

Event and Delegates in C#


Connect with me on social media:

My blog



Comments (7):

By anonymous    2017-09-20

Should I create an individual repository for each? For instance one repository for enquiries, another for user usage metrics? Is there any overhead or penalty for doing this?

Yes. No.

Generally you want to have one repository per entity type because each entity type is going to more than likely require operations specific to its type beyond the cliche CRUD operations. The aim of the repo is to eliminate duplicate data query logic that would otherwise be littered about your application.


interface IRepo { CRUD }

protected abstract class RepoBase<T> : IRepo 
   // CRUD implementation

public class PatientRepo : RepoBase<Patient>
    List<IPatient> GetAllTerminallyIllPatients();

public class MusicRepo : RepoBase<Music>
    List<ISong> GetAllSongsByArtist (string artist);

Note how each repo in my feeble example is customised to the entity type. If you didn't do this your single repo would quickly

  • become hard to find that method you're after
  • unmanageble with the potential for 100s of methods
  • lead to increased probability of source control conflict due to all code being in one file

You might want to consider splitting your repos into repos and unit of work classes because:

Repositories should not have semantics of your database. It should be like a collection of objects in memory and should not methods like update and save. - Mosh

You can learn more from the tutorial in the link below.

Does having multiple repositories increase resource usage?

Generally no, because for any given operation, all of your interested repos would be attached to the same database context instance. It is the context that is expensive, not the repo.

Tell me more

Original Thread

By anonymous    2017-09-20

You're almost in the right direction. However, the ViewModel in this case should reside in the application layer, i.e. your MVC layer. The service layer should in turn return a data transfer object, more commonly known as the DTO.

Think of the ViewModel as a simple POCO class that is built for the View, it can be a collection of various DTO returned by various services from your service layer.

Benefits of DTO

  1. You are not directly exposing your domain entities, i.e your EntityFramework POCO classes. However, a case can be made for a project small enough to avoid DTO all together.
  2. In case in the future you decided to add an WebAPI function along your MVC project, say, for an iPhone application. The new application uses the WebAPI that also consumes the service layer, most of the service layer codes can be re-used since they return DTO classes and not ViewModel that is constructed for the View itself.

For your Data Access layer, no one explains better than this guy. Entity FrameWork With Repository Pattern

As for project structure, I would suggest an onion architecture. Onion Architecture. If you can understand this article well enough, you should be all set.

Original Thread

By anonymous    2018-02-26

I watched this video and read this blog post. There is something in this post confused me; The last part of the post. In the last part Mosh emphasized, Repository should never return IQueryable, because it results in performance issue. But I read something that sounds contradictory.

This is the confusing part:

IEnumerable: While querying data from database, IEnumerable executes select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.

IQueryable: While querying data from database, IQueryable executes select query on server side with all filters. Hence does less work and becomes fast.

this is another answer about IQueryable vs IEnumerable in Repository pattern.

These are opposite of Mosh's advice. If these are true, why we should not use IQueryable instead of IEnumerable.

And something else, What about situations that we want to use OData; As you know it’s better to use IQueryable instead of IEnumerable when querying by OData.

one more thing, is it good or bad to use OData for querying e-Commerce website APIs.

please let me know your opinion.

Thank you

Original Thread

By anonymous    2018-06-22

Case #1

When you're "placing an order", you may have to call the "Insert" methods of the "Order Repository" and the "Update" method of the "User Repository" (e.g: to deduct store credit).

Both of these methods should be atomic, and the entire use case is a Unit of Work. The Unit of Work's job, is to ensure that both methods succeed or fail as a whole.


"A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work." - Martin Fowler

If you're looking for a catch all Unit of Work / Repository Pattern, you won't find one, and even less likely if you're looking for a framework agnostic implementation.

This is the most honest Entity Framework Repository and UoW tutorial on the interwebs (Excerpt from:

There are many ways to implement the repository and unit of work patterns. You can use repository classes with or without a unit of work class. You can implement a single repository for all entity types, or one for each type. If you implement one for each type, you can use separate classes, a generic base class and derived classes, or an abstract base class and derived classes. You can include business logic in your repository or restrict it to data access logic. You can also build an abstraction layer into your database context class by using IDbSet interfaces there instead of DbSet types for your entity sets. The approach to implementing an abstraction layer shown in this tutorial is one option for you to consider, not a recommendation for all scenarios and environments.

Out of the box, OR/M's usually provide some form of repository and unit of work patterns that are already abstracted away for you and the implementation is hidden from the consumer (you).

If you need to persist data in XML, your repository is probably going to look very similar, but your UoW is going to look a lot different, and you're not going to have any transaction/rollback support.

The "clean code" way would be to architect your as many levels of abstraction you need to satisfy SOLID principles.

There is a pretty good video on how you can architect your repositories and UoW without actually depending on any persistence framework, however I wouldn't call it completely framework agnostic, as it smells like entity framework.

Mosh Hamedani Repository Pattern with C# and Entity Framework, Done Right

Case #2 has an underlying architecture issue in my opinion.

LoginController needs to "Log in a user" and "Give Rewards Points" -- doing 2 things.

PurchaseController needs "Complete a purchase" and "Give Rewards Points" -- doing 2 things

The solution is to create a RewardsPointsController, and have both LoginController and PurchaseController call the RewardsPointsController to decide if a User gets rewards points or not based on the event type or date.

It becomes clearer if you think of it this way..

If a user logs in during a promotion period, and the RewardsPointsController fails to add rewards points, should the entire transaction fail? Then the user would not be able to log in -- Rewards points can be fixed later by a Customer Service call, but if the user can't log in, or complete a purchase, you've lost business.

Original Thread

By anonymous    2018-08-06

I have implemented Repository pattern with Unit of work but have some architectural issues.

For example, lets say I am creating a used car parts online store. While I have operations on my DB I also have operations I need to perform on remote API's from different scrap yards e.g. need to run searches, availability updates and more...

I decided to try unit of work and repository pattern

Did things mostly like Mosh Hamedani but for core 2.1 From videos like this one

Unit of work and repositories work OK and make sense so long as I am using EF(or something else to communicate with DB) but it doesn't make much sense if I am to get some of the data trough different web apis. (e.g. getting list of cars on the market from different APIs whose handling and retrial is similar but different - I am retrieving different implementations of the same interface by key)

First I don't like the fact that I have all instances for all repositories inside my unit of work but need only one in most of the cases. I know it helps to reuse context transaction without wrapping it in my own but still its silly having unnecessary instances.

Second Should I implement retrieval logic and handling for remote api's also inside a repository and unit of work or maybe ditch unit of work and do something else? Keep just repositories? (Someone once mentioned facade pattern which I'm not familiar with)

I tend to overengineer things and right now I'm very confused. Any insight is helpful.

Original Thread

Submit Your Video

If you have some great dev videos to share, please fill out this form.