Entity Framework + Repository + Unit of Work

Darf Zon picture Darf Zon · Jan 4, 2012 · Viewed 12.8k times · Source

I'm thinking about starting a new project using EF 4 and going through some articles, I found some articles about EF with repository pattern and unit of work

( http://tdryan.blogspot.com/2011/03/another-entity-framework-4-repository_15.html and http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx)

I'm using the first one (part1, part2 and part3). They are very similar.

I'm a newbie in this scenario. I'm confusing between these two posts. I've create everything but I have no idea how can I start using the context and add some entities to it. I posted the second link because posted a way to implement it. The ObjectContext is derived from IUnitOfWork, so I'm confused to chose which of these two is better to use.

Answer

Wouter de Kort picture Wouter de Kort · Jan 4, 2012

Your question is not stupid! Getting started with UnitOfWork and the Repository patterns takes some time.

First, to get some terminoloy right. A UnitOfWork encapsulates a set of actions and groups them together. So you can for example create a customer, a product and a corresponding order in one logical group.

A Repository gives you a single point of access to entities and most of the time has some specific methods for retrieving data.

Multiple repositories can be used in one single transaction, that's why they share a UnitOfWork.

In the example you posted, the T4 files create some Repository interfaces. One is a readonly with methods to select entities but the other Repository has methods like Add and Delete.

So if you want to add an entity, you need to first construct a UnitOfWork and then instantiate a Repository for the entity type your working with (CustomerRepository or ProductRepository for example). You can then use the Add method to add entities to a Repository. When you're done working with your repositories you would call UnitOfWork.Commit() to save your changes to the database.

IUnitOfWork unitOfWork = new EFUnitOfWork();

IRepository<Customer> customerRepository = new CustomerEFRepository(unitOfWork);

Customer c = new Customer();

// init customer

customerRepository.Add(c);
unitOfWork.Commit();

In the example you posted, Dependency Injection with StructureMap is used. This is a whole other topic, but it means that you don't construct the UnitOfWork and Repository directly but that they are 'injected' into your code using some configuration that you've setup.