Repository Pattern with C# and Entity Framework, Done Right

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#

Generics

Connect with me on social media:

My blog

Facebook

Twitter


Posted

in

by

Tags:

Comments

35 responses to “Repository Pattern with C# and Entity Framework, Done Right”

  1. Dominic Pascasio Avatar

    Thank you! This is the best introduction to UoW IMO. I have a few things to change though, I hope you let me know your thoughts:

    – GetAll is not desirable to all my entities, some if not most are large datasets and I dont want to expose that. I'll remove it.
    – Not all my keys are int so I'll remove Get<TEntity>(int id) or change it with (object[] keyValues).
    – Find with predicate is not desirable either, if I'm using dapper to one of my repo, I don't want to be querying the Expression to get the parameters.
    – I'm also not into Remove where the parameter is an entity. I will have to query the item first or instantiate an entity and assign a key to it just to delete an item.
    – Also, I will rename Repository class to DbContextRepository and put it under something like Repository.EntityFramework namespace since it is tied to EF.

  2. Ruwantha Ratnayake Avatar

    once working with the unit of work, how to modify the EntityState of DbEntityEntry object.
    Ex: db.Entry(author).State = EntityState.Modified;

  3. Clayton Wakefield Avatar

    Really great video Mosh! I just brought your Udemy course for Entity Framework – love your teaching style man, very clear and well explained – this is the best explanation I have seen for the Repository pattern, hence my decision to buy the course. Cheers!

  4. faridul huk Avatar

    How to handle the situation when something added to entity and retrieve that entity again which is not saved to data base yet. Loading from local context.

  5. Emilio Mota Avatar

    Totally agree to use a pattern when you NEED to otherwise you are compromising the time to deliver a project. At least that was my situation. THE CLIENTS NEED SOMETHING THAT WORKS, THEY DON'T CARE IF YOU USED A PATTERN X OR Y OR Z to get the same result.But of course, if you have time and you are really good and fast why do not give it a try right?

  6. xhiris Avatar

    Abolutely brilliant! This finally made everything 'click' on using the Repository pattern with EF6. I'd avoided it because it seemed like far too much work for too little benefit vs. using DbContext directly,

  7. John Olawale Avatar

    Great tutorial. Thanks

  8. Kamdem Kakengne Avatar

    Nice and clean ! I like the way you explain things ! Thanks a lot Mosh !

  9. Gaurav Pathare Avatar

    This channel is gold mine for C# Beginners and Aspirants.

  10. alberto .medina Avatar

    Great presentation. love it, now where I can find this implementation on MVC 5?

  11. V20 User Avatar

    Hi Mosh, This is great presentation. I have 3 questions.
    1. Since dapper orm has no dbcontext, where should we put the persistance part because repository acts only as in memory collection and no sql execution here?
    2. When we want to update data just for one domain entity (no need transaction), do we still need UoM to do that?
    3. One transaction need to create 1 UoM implementation file, or it is permissable to combine all in one UoM class?

    Looking forward to hearing from you

  12. Chris Johnson Avatar

    You say there is no need to update in the repository pattern. But, actually you do need to update records. Thanks for leaving out that extremely important piece of information!!

  13. jovica milenovic Avatar

    You said that that one point for using the repository pattern is decoupling the application from the underlying ORM. But if you supply DbContext (System.Data.Entity) as a parameter to the repository constructor it is coupled to the EF ORM, right (at 17:08)?

  14. Fernando Máximo Torres Avatar

    why return IEnumerable intead IList?

  15. Pierre Nilsson Avatar

    Best explanation I've yet to see of the repository pattern.

  16. Gabriel Pauna Avatar

    "please don't do over-engineering " totally agree !

  17. Josh Monreal Avatar

    Hi Mosh,

    I have learned so much from this lecture and I have already subscribed to your Entity Framework class in Udemy. I do have a question though. Does the concept of UnitOfWork already implies that the application uses dependency injection? The reason I am asking this is because in my current project, each controller's constructor has the [Inject] attribute with parameters such as IAuthorRepository _authorRepo, etc. If we are to use UnitOfWork do we still need to use Ninject?

  18. Tuan Pham Avatar

    really easy to listen, easy to understand! Thanks

  19. Matthew Krieger Avatar

    @Mosh – Why not include the Add() and Delete() methods in the Unit of Work class as well? Doesn't the same principal (that applies to the Update() and Save() methods) apply?

  20. M L Avatar

    I have been using EF since it came out around 2008/9 and have come to the conclusion that implementing the Repository and UoW pattern on top of EF gives you almost nothing…especially the UoW. The DbContext is injectable so you can let your DI container control the lifetime of the context. In most web site or web services this is going to be InRequestScope. IDbSet<T> is mockable, so you can mock your Add(), AddRange(), Remove(), RemoveRange(), etc. for unit tests. The same applies to basic queries on the IDbSet<T> which you can replace with in memory mock data. EF objects themselves are also POCO so they know nothing about EF itself. Most of the time, they serve perfectly fine as domain entities / business objects, especially if you are OK with anaemic domain models (anaemic domain model is NOT an antipattern…but that's a different debate).

    Complex queries should be encapsulated and reused, but you can build a context wrapper by deriving from the context for these…or even put them on the contexts partial class. Stored Procs that are mapped into EF just become methods on the context.

    The only one concrete argument for Repo + UoW is the tired "what if you want to change your ORM." UI technologies change rapidly, but in 12 years of my career not once have I worked on a project where the data access technology was changed independently of other changes in the application. I have concluded based on experience that it is not a scenario worth engineering for.

  21. lindeberg Avatar

    Is this pattern unnecessary if I find myself with 10 repositories but only one or two is actually extending with query methods?

  22. Flexabust bergson Avatar

    Hi, great tutorial! Could you post what your project architecture looks like?

  23. Nelson Rothermel Avatar

    It seems like this works well when your ORM directly works with your domain entities. If you need to separate the two (e.g. ORM limitations force bad practices on domain), then it all breaks down, starting with the base Repository. Still a good intro, and good to not expose IQueryable.

  24. rallye2011 Avatar

    Is it possible to use this pattern without an ORM?
    Can you show us how?

  25. ilia deviatov Avatar

    Hi Mosh, thank you for your video it inspired me to include repositories in my project. However, can repositories return a viewModel (result of joined tables) if not how is that resolved in repository pattern. I asked a similar question on SO: http://stackoverflow.com/questions/43933380/asp-mvc-repository-patten-dealing-with-complex-queries-and-viewmodels/43935683#43935683

  26. Asad Moosa Avatar

    I would like to take a look at a full coding including CRUD (Database First Approach). And I do hope it also uses multiple tables for CRUD (Like the drop down list of another table in the form to add/update).

  27. Stesvis Avatar

    hey which course is this in the list?

  28. Josh Monreal Avatar

    Very informative tutorial. Thank you so much for this.

  29. Ravi Kanth Avatar

    You're awesome Mosh … Thanks

  30. Rishav Kumar Avatar

    U are awesome… man.. You just cleared all my doubts regarding these…

  31. Sandeep Ramani Avatar

    Why No Update method in Repository? How you gonaa update entity using UnitofWork class? Just did not get it what you explained in videos. so need to understand it.

  32. Abdelwaheb HADJ AYED Avatar

    Thanks Mosh, but i wonder if this leads to a performance issue with all these encapsulations. I tested your code and it takes between 6 and 7 sec to show me the result of this query :
    var courses = unitOfWork.Courses.GetTopSellingCourses(5);
                    foreach (var course in courses)
                    {
                        Console.WriteLine($@"name = {course.Name}");
                    }

    18:21:05
    name = C#
    name = PHP
    name = Excel
    name = VB.net
    name = Word
    18:21:13

Leave a Reply

Your email address will not be published. Required fields are marked *