I am using Entity Framework and I am trying to learn Unit of Work pattern in combination with Repository pattern.
From what i understood until now, Unit of Work is responsible with keeping track of the changes made to the entity objects. However, isn’t the DataContext doing the same thing?
So, implementing unit of work pattern isn’t like “forcing” you to use the same context across all methods?
public class EFUnitOfWork : IUnitOfWork
{
EFContext context = new EFContext();
public void Commit()
{
context.SaveChanges();
}
}
public class ProductsRepository(IUnitOfWork unitOfWork)
{
/* CRUD methods here */
}
public void InsertProducts()
{
var unitOfWork = new EFUnitOfWork(); // <-- this will normally be injected via constructor
var productsRepository = new ProductsRepository(unitOfWork);
productsRepository.Insert(new Product { Name = "Product 1", Description = "Description" });
productsRepository.Insert(new Product { Name = "Product 2", Description = "Description" });
productsRepository.Insert(new Product { Name = "Product 3", Description = "Description" });
unitOfWork.Commit();
}
Is this the right way of using Unit of Work with Entity Framework?
Yes, you share the same DataContext. Here’s a tutorial that will help you: 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