During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?
Why Avoid Using Repository Pattern with Entity Framework?
asp.net-mvcentity-frameworkunit-of-work
Related Topic
- Design Patterns – Repository Pattern Without Entity Framework
- If Repository Pattern is overkill for modern ORMs (EF, nHibernate), what is a better abstraction
- Xamarin Development – Web API vs Entity Framework with Repository Pattern
- Entity Framework 6 – Should It Be Used with Repository Pattern?
- C# – Is Unit of Work Pattern Needed with Repository Pattern?
Best Answer
I don't see any reason for the Repository pattern to not work with Entity Framework. Repository pattern is an abstraction layer you put on your data access layer. Your data access layer can be anything from pure ADO.NET stored procedures to Entity Framework or an XML file.
In large systems, where you have data coming from different sources (database/XML/web service), it is good to have an abstraction layer. The Repository pattern works well in this scenario. I do not believe that Entity Framework is enough abstraction to hide what goes on behind the scenes.
I have used the Repository pattern with Entity Framework as my data access layer method and am yet to face a problem.
Another advantage of abstracting the
DbContext
with a Repository is unit-testability. You can have yourIRepository
interface to which has 2 implementations, one (the real Repository) which usesDbContext
to talk to the database and the second,FakeRepository
which can return in-memory objects/mocked data. This makes yourIRepository
unit-testable, thus other parts of code which usesIRepository
.Now using DI, you get the implementation