Advertisement
Advanced C#, Design Patterns in C#

How would you implement the Unit of Work pattern alongside the Repository pattern to coordinate multiple repository changes within a single transaction?

Short answer

Unit of Work tracks all changes made across multiple repositories during a business operation and commits them together in ONE atomic transaction (typically via SaveChanges() in EF Core) — this ensures related changes across different repositories either ALL succeed or ALL fail…

Save C# mock interview
Advertisement
AModel answer
Unit of Work tracks all changes made across multiple repositories during a business operation and commits them together in ONE atomic transaction (typically via SaveChanges() in EF Core) — this ensures related changes across different repositories either ALL succeed or ALL fail together, maintaining data consistency.
public interface IUnitOfWork : IDisposable {
  IRepository<Order> Orders { get; }
  IRepository<Customer> Customers { get; }
  Task<int> SaveChangesAsync();
}

// Usage
unitOfWork.Orders.Add(newOrder);
unitOfWork.Customers.Update(customer);
await unitOfWork.SaveChangesAsync(); // both changes committed together, atomically
Real-world example
Ensuring an order placement (which updates both an Orders table AND a Customer's loyalty points) either fully succeeds or fully rolls back together.
Likely follow-ups
  • Does Entity Framework Core's DbContext already implement the Unit of Work pattern internally, making a separate abstraction sometimes redundant?
Related topics