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




About this tutorial:

Video duration: 26:24
🔥Get the COMPLETE Entity Framework course (80% OFF – LIMITED TIME):

Confused about the repository pattern? This tutorial explains it all.

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…

Post Author: OfficeTutes.com

Apple lover, ICT and LEAN consultant, MS Office lecturer My other website with video tutorials - Tutorials, guides and news for iPhones and iPads

48 thoughts on “Repository Pattern with C# and Entity Framework, Done Right | Mosh

    El Dorado

    (December 7, 2018 - 2:52 am)

    anyone knows what visual studio theme Mosh using?

    George Kopadze

    (December 7, 2018 - 2:52 am)

    Great Tutorial Mosh, Thank you for that. Please make tutorials about design patterns. It would be great if you explain more in details. And can you tell me what benefit can we get from unit of framework and repository with EF core? Thank you very much

    Pascal Declercq

    (December 7, 2018 - 2:52 am)

    I have a question about the decoupling of the application from the persistence framework. In the source code that comes with the video, domain, persistence and application are in the same project. I separated domain and persistence each in an own project and that worked but with the condition that the entity framework was added to the main application project although all persistence logic was moved away from there. So no real decoupling. How could the solution be set up that it could use different persistency projects whithout having to reference them all or their underlying libraries?

    Fronz1K

    (December 7, 2018 - 2:52 am)

    I can't see why do you have Interfaces if you use classes directly everywhere.

    karr

    (December 7, 2018 - 2:52 am)

    1- Why this in Repository class?:
    protected readonly Context Context;
    public Repository(Context context)
    {
    Context = context;
    }
    And why this in CourseRepository class?:
    public PlutoContext PlutoContext
    {
    get { return Context as PlutoContext; }
    }

    But why not just this in Respository class?:
    protected readonly PlutoContext Context;
    public Repository(PlutoContext context)
    {
    Context = context;
    }

    2- Why is UnitOfWork class with a constructor which takes a DbContext (PlutoContext)?
    Why not?:
    In controllers:
    var unitOfWork = new UnitOfWork();
    In UnitOfWork class:
    public UnitOfWork()

    {

    _context = new PlutoContext();

    // …
    }

    dave_by_day

    (December 7, 2018 - 2:52 am)

    16:11 – An expression on funk!

    Moslem Hady

    (December 7, 2018 - 2:52 am)

    Laxman Nagtilak

    (December 7, 2018 - 2:52 am)

    it is difficult to update the models with add only . entityframework needs state updation as well. How to do such things with this repository pattern Context.Entry(entity).State = EntityState.Modified;

    Peter Andersson

    (December 7, 2018 - 2:52 am)

    Why on earth have the predicate method in the repository! Now you repeat the predicate instead, violating one of your rules, also you limit your self to orms that support it!

    imran

    (December 7, 2018 - 2:52 am)

    Hello Mosh I really like your style of teaching and you make it really easy to learn, I am trying to learn Domain Driven Design but I cant find any tutorial created by you, can you please do a DDD tutorial for us as well

    Tim Tom

    (December 7, 2018 - 2:52 am)

    I'm confused as the source code for the video isn't the same as the one shown in the video. Would it be possible to get that code please dude? Love the lesson and want to implement it in my project. Thanks 🙂

    Vussan Bhele

    (December 7, 2018 - 2:52 am)

    How to use DI instead of using new keyword to create instances of repositories inside unit of work?

    Fahad Ali

    (December 7, 2018 - 2:52 am)

    This SqlTransaction has completed; it is no longer usable. entity framework . we are getting this error when calling savechanges of unitofwork , what can be the solution. our environment is multi threaded and asynchronous

    Jez

    (December 7, 2018 - 2:52 am)

    The trouble with this seems to be that your TEntity classes are being used both by EF and as domain objects, and not mapped via something like AutoMapper. So if you want your domain objects to have a different structure to the objects that EF can map directly to the database this won't work.

    Bora Aydın

    (December 7, 2018 - 2:52 am)

    What if id is type of Guid, then your generic repository will not work. Here is iEntity comes to play. Your domains should inherit from iEntity<T>, so you can query based on id

    женя гуньков

    (December 7, 2018 - 2:52 am)

    Just want suggest a small improvement. In AuthorRepository you can avoid cast "return Context as PlutoContext" by saveing Context as private field during initialization
    "public AuthorRepository(PlutoContext context)"

    Marvin Cunanan

    (December 7, 2018 - 2:52 am)

    Mosh, can I use entry framework using Mysql Database?

    DaCh Mick

    (December 7, 2018 - 2:52 am)

    I like this pattern. Curious where to implement it in my MVVM WPF, though

    Mohamed keblawy

    (December 7, 2018 - 2:52 am)

    I Cannot download the source code .please!! send it to me

    Kristifor Milchev

    (December 7, 2018 - 2:52 am)

    You have solid understand of the repository pattern however I couldn't miss the most ridiculous thing that I've ever heard since long time ago. How is having a repository in front of the entity framework solve code changes on update the repository wont work because its still using entity framework the example was a bit irrelevant and controversial.

    yadavendra yadav

    (December 7, 2018 - 2:52 am)

    Hi, I liked the video, but my only question is why one wanna make ICourseRepository inherit from IRepository when CourseRepository is already inheriting from Repository

    Asif Zaffar

    (December 7, 2018 - 2:52 am)

    Hi Mosh, can you share the source code.

    Django MOC

    (December 7, 2018 - 2:52 am)

    Great video.

    John Nyingi

    (December 7, 2018 - 2:52 am)

    Github link would like to go through a full example

    qwarlock Z

    (December 7, 2018 - 2:52 am)

    Good video but I think most people are using a Service Layer and DAO pattern. So that already decouples the persistence layer from your application code. This seems like it is another layer of abstraction between the service layer and the DAO layer. Sping Data does use now a repository for accessing persistence information. But the recomendation is that this still goes in the service layer. So it is a replacement of the DAO layer or at least a new version of DAO.

    Zach B

    (December 7, 2018 - 2:52 am)

    Mmmm… Smell that? It's not my code. That's the smell of over-engineering.

    Parmeshwar Rathod

    (December 7, 2018 - 2:52 am)

    Keep up the good work

    Jin Izzraeel

    (December 7, 2018 - 2:52 am)

    Why not use "using" block in MVC applications? Can you explain please? Is there a particular reason?

    Łukasz Kowalski

    (December 7, 2018 - 2:52 am)

    Repository in UOW is an anti pattern and using the repository to get persistence model as well. I recomend for all of you lazy busters chek definition of Repository pattern and consider what mean "for accessing domain objects.". Persistence models of ORM is not a domain object this part of infrastructure that represent table in DB.

    He made some sort of wrap on ORM wich is not necessary if you'r using good orm like NHibernate.

    KangoV

    (December 7, 2018 - 2:52 am)

    What if you want to change an entity. Do you have to remove and then add?

    Mike Barger

    (December 7, 2018 - 2:52 am)

    IMO, the “collection-like interface” is the least important and most out-dated portion of the repository pattern. The most important part of the pattern is to isolate the rest of your application from the persistence logic. You typically don’t want to reuse repository methods. Since your business logic shouldn’t be in the repository, you don’t want multiple code paths reusing a repo method like SaveArticle(Article article). Instead reuse the same service method that calls the repo so the same business logic is enforced. Too many coders try to get cute/clever with generic repositories, exposing IQueryable, etc. EF performs poorly enough all by itself. It doesn’t need help being slower by the n+1 problems created by not writing custom linq queries that specify the include. Of course it always depends on the specific constraints of the application. Thank you for your great videos.

    Moslem Hady

    (December 7, 2018 - 2:52 am)

    بسیار عالی جناب همدانی 🙂

    HystericallyRoxas

    (December 7, 2018 - 2:52 am)

    Okay, this makes sense, thanks a lot for the video.
    That said, here go a couple of questions 😀
    how do you go about accesing FK references, using anonymous objects to not pull the entire rows of each table you're working on, etc?
    this doesn't seem to be a high performance pattern for what I can see, it seems to be directed to code flexibility and readability.
    What about View Model conversion? it's pretty standard to have a couple of different view modes for every object (used in pages, grids, dropdowns, etc), do these get implemented on the repository as well? Seems a bit odd

    Kutlo Maduma

    (December 7, 2018 - 2:52 am)

    The way you explain things is so uncomplicated you almost make it seem like this stuff is easy. Thanks a load mate. Your tutorials are excellent.

    TheRealIceman10

    (December 7, 2018 - 2:52 am)

    Why not return an IQueryable? You dont break ORM abstraction with it, but you dont have to create a method in the Repository if you want to make a special query just once in the code. For example, I want to query people with a name starting with "A". If I use GetAll, I will get all the people of the Database. I could use Find, but I don't like that method for the same reason someone stated here. So why not return the IQueryable?

    Kevin Marois

    (December 7, 2018 - 2:52 am)

    I have a question regarding the Unit of Work. I assume that in a real-world application the Unit of Work class would be in the DAL and that you would pass in any needed parameters?

    Daniyar Kaliyev

    (December 7, 2018 - 2:52 am)

    The whole point of having repository patterns is to decouple Data layer from Business layer. Thus changing Data layer, i.e. changing underlying persistence mechanism like EF to something else like nHibernate should not require changes in Business layer. This is not the case here

    Royke Senewe

    (December 7, 2018 - 2:52 am)

    how to update data? no update method?how about if the entity is disconnected?

    Royke Senewe

    (December 7, 2018 - 2:52 am)

    Where is the update

    metabuddy

    (December 7, 2018 - 2:52 am)

    This works with 10 or less tables. It does not scale, if you're working with 500 tables.

    javier

    (December 7, 2018 - 2:52 am)

    what if i need to return an object with two properties, one of each model. where should i define the class that will be returned and its ok that a repository returns something that is not an entity?

    Pramod Kumar Singh

    (December 7, 2018 - 2:52 am)

    Hey Mosh,i think you also need come on Plural Sight other than Udemy

    Carlos Nuñez

    (December 7, 2018 - 2:52 am)

    Hi Mosh, one question, how many UoW should i have to have?, assuming that im only working with one single context, one UoW for all my repositories, or as many UoW i consider necessary?
    Thanks!

    Mark Sandy

    (December 7, 2018 - 2:52 am)

    Nice and simple. One question: Why do you use 'AsList()' to return an 'IEnumerable'? Use AsEnumerable or 'AsArray'. Why first create a list and then not benefit of it's methods?

    Josh Monreal

    (December 7, 2018 - 2:52 am)

    You mentioned that there should be no Update method inside a repository. In Entity Framework it's fine because DbContext has a ChangeTracker method which keeps track of the state of the objects. But what if the other ORM that you would like to use does not implement one (i.e. classic ADO.NET which uses SqlCommand)? How then can you implement the Update method?

    Technotips - Ashish

    (December 7, 2018 - 2:52 am)

    Nice video .. Since you are an experienced youtube creator, I want to collaborate with you. Yours and mine channels are same. We can help each other to make the useful content to reach more audience and to make them benefited wih the real time videos based on MVC. We can provide the link of videos of similar topic in our video description. If you are agree then please contact me. Hope to hear from you..

    Alok Babu

    (December 7, 2018 - 2:52 am)

    Thanks for explaining. Could you tell me how to initialise a controller with other other services dependency injected along with Unit of work?

    Volodya Senchak

    (December 7, 2018 - 2:52 am)

    Really good explanation of Repository pattern.

Leave a Reply

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