Wednesday 6 October 2010

Applying Generic Repository and Unit of Work Pattern to Entity Framework

There is a very good article (Testability and Entity Framework 4.0) talking about the Repository and Unit of Work pattern and how we can do that using Entity Framework. However, I don't like the way the IRepository and IUnitOfWork were designed. Firstly the IRepository interface has too many unnecessary methods and some are based on assumption, for example FindById(int id), what if an entity uses GUID as primary key? Also the FindAll() and FindBy() methods are returning IEnumerable which will cause the lambda expression to be evaluated when returned from these methods. Secondly the IUnitOfWork has reference to all repositories, what if we add a new repository, do we have to update the IUnitOfWork interface? I think this is a bad design.

I have re-structured the IRepository and IUnitOfWork interfaces as follows,




The IRepository interface will have Add(), Delete() and Attach() method to track entities, it also has a readonly reference to IUnitOfWork to Commit(), and there is another readonly properties "Entities" which is of type IQueryable, so that it can be queried using LINQ. We don't really need methods like FindById() defined in the interface as they be easily added using extension methods.

Two concrete implementation for Entity Framework,


Using the EFRepository and EFUnitOfWork in MVC



To save a new event,


Simple and elegant.