Hussein
Hussein

Reputation: 991

Generic Repository should use Unit of Work or DbContext directly

  1. When I use Generic Repository with Entity Framework, do I need to use Unit of Work because to my knowledge UOW coordinate between multiple repositories. Or let Generic Repository work directly on the DbContext because UOW is not needed.

  2. Which is best practice : use generic repository or implement repository class for each entity type.

Upvotes: 0

Views: 1747

Answers (1)

Albert
Albert

Reputation: 437

I don't know which generic repository you are refering to, but here is my experience with A generic repository.

In general, a unit of work or repository is not needed with EntityFramework. EntityFramework does it all.

However, in my first EF project I found myself creating a factory class that handed out and saved all entities. The class was doing that without doing the complete work of a unit of work, nor providing a standardized interface like a repository does. The huge class was in need of some structure. So, my personal advice is against one big repository for all entities, this repository will grow and will be increasingly difficult to maintain. If you think of such a class you better use EF as it is.

In the second project I use a UnitOfWork and generic repository. This suits my purposes much better. One unit of work to do the save operation, saving all changes in one save operation and the same interface for all repositories. Two classes of which I only have to change the unit of work to accommodate a new entity. The unit of work also hides the use of the dbContext which to my opinion causes ugly code.

I do not use a fancy unitofwork or generic repository (I found mine at: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application), just enough to have some guidance in implementation.

I agree with Gert in his immediate reply: it is all about personal preference.

Upvotes: 2

Related Questions