Unit of Work + Entity Framework + Repository

c# design-patterns entity-framework repository unit-of-work


Going through several publications, I discovered some articles regarding EF with repository pattern and unit of work as I consider beginning a new project using EF 4.

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

I'm making use of the first (part1, part2 and part3). They have a lot in common.

I'm fresh to this situation. I'm not sure which of these two postings is which. Even though I've created everything, I have no clue how to use the context or add any things to it. I included the second link since it provided instructions on how to utilize it. TheObjectContext originates fromIUnitOfWork I'm not sure which of these two is best to utilize, therefore I'm perplexed.

1/4/2012 4:21:38 PM

Popular Answer

Your query is not foolish! Starting out withUnitOfWork both theRepository Patterns take time to develop.

First, let's clarify a few terminologies. AUnitOfWork encompasses a series of acts and collects them all in one place. As a result, you may logically put together, for instance, a client, a product, and the related order.

A Repository provides you with a single point of access to entities and often has some unique techniques for data retrieval.

They have a common interface since several repositories may be utilized in a single transaction.UnitOfWork .

The T4 files in the sample you supplied produce someRepository interfaces. One has ways to select entities and is read-only, whereas the otherRepository has techniques likeAdd and Delete .

Therefore, in order to add an entity, you must first create aUnitOfWork and after that, launch aRepository for the entity type that you are using (CustomerRepository or ProductRepository for instance). Then, using theAdd way of including things in aRepository After finishing up with your repositories, you would dialUnitOfWork.Commit() to commit your modifications to the database.

IUnitOfWork unitOfWork = new EFUnitOfWork();

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

Customer c = new Customer();

// init customer


You utilized Dependency Injection and StructureMap in your sample. This is a whole other subject, yet it implies that you don't create theUnitOfWork and Repository directly, but rather via the use of a configuration you've put up, they are 'injected' into your code.

9/3/2013 12:49:51 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow