Roadmap › Design Patterns (GoF + Enterprise) in C# › Module: Enterprise and Cloud Patterns
Lessons in this course (18)
15. Repository and Unit of Work
Intermediate★ Must knowLesson 15 of 18
Repository — a collection-like abstraction over data access. Unit of Work — tracks changes and commits them in one transaction.
csharp
public interface IOrderRepository
{
Task<Order?> GetAsync(int id, CancellationToken ct = default);
void Add(Order order);
}
public interface IUnitOfWork { Task<int> SaveChangesAsync(CancellationToken ct = default); }
public class OrderRepository(AppDbContext db) : IOrderRepository
{
public Task<Order?> GetAsync(int id, CancellationToken ct) => db.Orders.Include(o => o.Lines).FirstOrDefaultAsync(o => o.Id == id, ct);
public void Add(Order order) => db.Orders.Add(order);
}Note: EF Core's DbSet<T> already is a repository and DbContext a unit of work. Many teams use DbContext directly. Others add repositories per aggregate to keep EF out of the domain and simplify testing. A generic repository over EF often adds little value — be ready to discuss this trade-off.