Bes-m M-bes
Bes-m M-bes

Reputation: 177

Unit of Work and common implementation

I have some questions regarding a common implementation of the UoW, Repository Pattern and EF:

public interface IAppUow
{
    void Commit();
    IRepository<Customer> Customer{ get; } // IRepository<T>
    IOrderRepository Order{ get; }         // implements IRepository<T>
} 

My questions are:

If I need to add a new repository of whatever type, I have to change the UoW. Is this a good practice? If not, is there a better way?

If I run Commit() ( context.SaveChanges ), it will save the state of all the contexts repository. Is this a good way?

Upvotes: 0

Views: 97

Answers (1)

Johnny Graber
Johnny Graber

Reputation: 1467

EntityFramework has already a Unit of Work build it. This enables you to call context.SaveChanges to store all your changes and you should therefore not wrap another Unit of Work Pattern around. You should use IRepository or IOrderRepository directly in your code.

To your questions:

  1. No. Depending on what your application does with Orders and Customers you could put them in one Repository. If you are foremost interested in Orders and only want to know where to ship your order this one repository and one context would be enough. And please do not wrap your UoW around EF.

  2. If you have only one EF context and multiple repositories using it you would save all pending changes when you call Save on the OrderRepository. Should you expect to save only the changes in the OrderRepository but not those in CustomerRepository you would have a problem. You can solve this using different EF context objects but then you will run into problems with what objects in your object graph get loaded by context1 and which ones by context2. I suggest you follow the EF way through and build one context and when you call save all your objects get saved. To split it you need to decide how your application works with the data.

You can find code examples for EF and ASP.NET MVC here.

Upvotes: 1

Related Questions