Volume 3 · Chapter 7 — Entity Framework Core and Data Access Engineering
Repository and Unit of Work Patterns
7.1 Introduction
The Repository and Unit of Work patterns abstract data access and transaction boundaries to isolate business logic from persistence. They became popular for decoupling and testability - but EF Core already provides much of what they offer, so applying them thoughtlessly adds ceremony without value. The mature view is: add these patterns only when they solve a real problem, and prefer domain-focused repositories over generic CRUD ones.
7.2 EF Core Already Implements These Patterns
This is the crucial insight:DbSet<T>already behaves like a repository (a queryable collection with add/remove), andDbContextalready is a Unit of Work (it tracks changes across entities and commits them together inSaveChanges). So a generic repository that merely wrapsDbSet, or a Unit of Work that merely wrapsSaveChanges, adds an abstraction layer with no added behavior - and even hides useful EF features.
flowchart TB
App["Application Service"] --> Repo["Repository (optional)"]
Repo --> Ctx["DbContext (already a Unit of Work)"]
Ctx --> Set["DbSet (already repository-like)"]
Set --> DB[("Database")] 7.3 When a Repository Earns Its Place
A repository is worth adding when it does more than forward calls: to keep EF types out of the domain, to centralize complex or reused query logic behind domain-meaningful methods, or to make the write model swappable and easily unit-testable. Domain-focused repositories -GetActiveCustomers(),GetCustomerWithAccounts()- express business intent and align with DDD, where a repository provides access toaggregate roots, not tables.
// Domain-focused repository: meaningful operations, hides EF, returns whole aggregates.
public interface IOrderRepository
{
Task<Order?> GetByIdAsync(OrderId id, CancellationToken ct); // aggregate root
Task<IReadOnlyList<Order>> GetOverdueAsync(CancellationToken ct); // domain query
void Add(Order order);
}
// vs a pass-through generic Repository<T> that just wraps DbSet - little value.
7.4 When Not to Use Them
For simple CRUD, or apps already well-structured aroundDbContext, a repository/unit-of-work layer is redundant ceremony - using EF Core directly in the application layer is simpler and legitimate. A generic repository can also hide valuable EF features (change tracking, eager loading, projections, async streaming) behind a lowest-common-denominator interface.
Does EF Core already implement the Repository and Unit of Work patterns? Do you still need them?
Yes, EF Core already provides both patterns, which is exactly why you often don’t need to add your own.DbSet<T>is effectively a repository: it’s a queryable collection of entities of a type, with methods to add and remove and the ability to query - the core of what a repository offers.DbContextis effectively a Unit of Work: it tracks changes across all the entities you’ve loaded and, onSaveChanges, commits them together in a single transaction - which is precisely the Unit of Work pattern’s job of coordinating multiple operations into one atomic commit. So a generic repository that just wrapsDbSetwith Get/Add/Remove, and a Unit of Work that just wrapsSaveChanges, add an abstraction layer that duplicates what EF already does, providing no new behavior while adding indirection - and worse, a lowest-common-denominator repository interface often hides genuinely useful EF Core capabilities like rich LINQ querying, projections, eager loading with Include, change tracking control (AsNoTracking), and async streaming, forcing awkward workarounds. So the answer to “do you still need them” is: not by default. You add a repository/unit-of-work layer only when it earns its place by doing more than forwarding calls - specifically to keep EF Core types out of your domain layer (so the domain depends on an abstraction, aiding Clean Architecture and testability), to centralize complex or frequently-reused query logic behind domain-meaningful methods rather than scattering LINQ, to provide domain-focused operations (especially in DDD, where a repository represents access to aggregate roots, not tables), or to make the persistence swappable and the write model easily unit-testable. For simple CRUD or apps already cleanly structured aroundDbContext, using EF directly in the application/service layer is simpler and perfectly legitimate. The seniority signal here is recognizing that EF Core is itself a repository and unit of work, and therefore not reflexively adding another layer - reserving these patterns for when they solve a real architectural problem (domain isolation, testability, meaningful domain queries) rather than applying them as boilerplate.
How do you design data-access boundaries in a large enterprise system where many teams write EF Core queries?
The problem to solve is that when many teams write EF Core queries directly wherever they like - inside controllers, scattered across services - data-access logic gets duplicated, inconsistent, and hard to maintain, and business-relevant query knowledge is smeared everywhere. So I design boundaries around business capabilities and expose meaningful domain operations, while keeping persistence concerns isolated and avoiding abstractions that add no value. Concretely, I organize data access by bounded context / business capability, so each capability owns its data and its access logic, rather than having a shared free-for-all over one giant model. Within a capability, I put data access behind an application/service layer (and, where it earns its place, domain-focused repositories for aggregate roots) that exposes intention-revealing operations -GetOverdueOrders,GetCustomerWithAccounts- rather than letting callers hand-write raw LINQ against the DbContext from controllers; this centralizes and names the important queries, removes duplication, keeps controllers thin, and keeps EF types out of the domain so the business logic depends on abstractions (aiding testability and Clean Architecture). Crucially, I apply this judiciously - I don’t impose a generic Repository<T> that just wraps DbSet everywhere, because that adds ceremony and hides EF features; I add repositories where they provide real value (domain isolation, reused complex queries, aggregate access) and let simpler areas use EF directly. I establish clear ownership - each team owns its capability’s data access - and shared standards/conventions so query patterns (projection, AsNoTracking for reads, pagination, avoiding N+1) are consistent, backed by code review and shared query helpers. For read-heavy or cross-capability reporting, I separate read concerns (a read model or CQRS query side) rather than contorting the transactional model. In a microservices setting, each service owns its database and no service queries another’s tables - communication is via APIs/events - which is the strongest boundary. So the design is: boundaries by business capability with clear ownership, meaningful domain-focused data-access operations behind a service/repository layer that isolates persistence and removes duplication, applied only where it adds value (not blanket generic CRUD abstractions), with shared conventions for query quality and separate read models for reporting - which keeps data access consistent, maintainable, and aligned to the business as many teams work on the system, instead of the sprawling, duplicated, controller-embedded queries that caused the problem.
7.5 Production Scenario
A large banking platform has many teams writing EF Core queries directly inside controllers, so data-access logic becomes duplicated and hard to maintain. The team introduces domain-focused repositories for aggregate roots and an application-service layer exposing meaningful operations, organized by business capability with clear ownership - while deliberately avoiding a blanket generic-CRUD abstraction that would hide EF features. Duplication drops, controllers thin out, and query knowledge is centralized where it belongs.
Chapter Revision Notes
- EF Core already provides these patterns: DbSet ≈ repository, DbContext ≈ Unit of Work.
- Don’t add a generic repository that just wraps DbSet - it adds ceremony and hides EF features.
- Add a repository when it isolates the domain from EF, centralizes reused queries, or provides aggregate access.
- Prefer domain-focused repositories (meaningful operations) over generic CRUD.
- Design data-access boundaries by business capability with clear ownership.