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:
http://programmingwithmosh.com/wp-content/uploads/2015/10/RepositoryPattern.zip

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

http://programmingwithmosh.com/courses

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

Event and Delegates in C#
https://youtu.be/jQgwEsJISy0?list=PLTjRvDozrdlz3_FPXwb6lX_HoGXa09Yef

Generics
https://youtu.be/gyal6TbgmSU?list=PLTjRvDozrdlz3_FPXwb6lX_HoGXa09Yef

Connect with me on social media:

My blog
http://www.programmingwithmosh.com/

Facebook
https://www.facebook.com/programmingwithmosh

Twitter
https://twitter.com/moshhamedani

Comments (5):

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.

e.g.

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

Submit Your Video

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