Tutorials Entity Framework Core Tutorial
Unit of Work Pattern with EF Core
Unit of Work Pattern with EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 52 of 100
Unit of Work Pattern with EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~6 min · Module 6: Advanced EF Core
What is this?
Unit of Work coordinates multiple repository operations sharing one DbContext and one SaveChangesAsync — one business transaction boundary.
Why should you care?
ShopNest checkout updates inventory and creates order through two repositories but commits once via IUnitOfWork.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public interface IUnitOfWork
{
IProductRepository Products { get; }
IOrderRepository Orders { get; }
Task<int> SaveChangesAsync(CancellationToken ct);
}
public class UnitOfWork(ShopNestDbContext db) : IUnitOfWork
{
public IProductRepository Products { get; } = new ProductRepository(db);
public IOrderRepository Orders { get; } = new OrderRepository(db);
public Task<int> SaveChangesAsync(CancellationToken ct) => db.SaveChangesAsync(ct);
}
What happened?
- Single DbContext instance backs both repositories.
- SaveChangesAsync once persists all staged changes atomically.
Practice next
- Inject IUnitOfWork Scoped per request alongside DbContext.
- Call repositories then single SaveChangesAsync at end of use case.
- Combine with explicit transaction for cross-context needs.
- Add BeginTransactionAsync wrapper on UnitOfWork.
- Register repositories lazy vs eager — measure DI complexity.
Remember
Unit of Work shares one DbContext session. One SaveChanges per business operation. Pairs naturally with repository interfaces.
ShopNest checkout unit
CheckoutHandler uses IUnitOfWork to add Order and decrement stock before single SaveChangesAsync.
Outcome: Partial updates impossible — both succeed or neither.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!