Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should i build a repository pattern with a unit of work on the top of my EF?

According to the MSDN the DbSet :

DbSet<TEntity> Class

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.Set method.


And according to the MSDN the DbContext :

DbContext Class

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.


So that the EF use the repository pattern and the UOW internally .

DbSet <----> Repository

DbContext <----> Unit Of Work

Why should I build a repository pattern with a unit of work on the top of my EF?

like image 653
Anyname Donotcare Avatar asked Feb 10 '16 18:02

Anyname Donotcare


2 Answers

Why should i build a repository pattern with a unit of work on the top of my EF?

Depends on how you want to manage your dependencies.

If Entity Framework is your abstraction layer and the database itself is the dependency, then Entity Framework does indeed already provide your repositories and unit of work. The trade-off is that your domain relies on Entity Framework. As long as that dependency is acceptable, you're good.

If, on the other hand, you want to treat Entity Framework itself as a dependency that can potentially be swapped out without making changes to domain code, then you'd want to create an abstraction as a wrapper around that.

Basically, it all comes down to where you draw the line of what is or is not an "external dependency". For some projects it doesn't matter, for some it's the physical database, for some it's the data access framework, etc.

like image 119
David Avatar answered Nov 15 '22 14:11

David


Why should I build a repository pattern with a unit of work on the top of my EF?

Because of the Interface Segregation Principle. The method signatures in DbSet and DbContext are basically a big low-level mess, there's a huge mismatch between them and what is typically expected in a Repository and a Unit of Work. In other words, if you use DbSet and DbContext directly, your Application Services code will suffer from leaky abstractions.

In your Application layer, you need to manipulate appropriate semantics. The code in that layer only needs to speak in terms of business transactions and large collections where you can fetch and store stuff. These are very high-level, minimalist abstract concepts. Entity Framework lingo is just too fuzzy and low-level for that, so you need to introduce other idioms - Repository and UoW.

like image 30
guillaume31 Avatar answered Nov 15 '22 15:11

guillaume31