Repository pattern in .NET: intent (a collection-like abstraction over persistence for an aggregate root), repository vs DAO/table gateway, why a generic IRepository<T> over EF Core leaks IQueryable, breaks the unit of work with per-repository Save, encourages Update() on detached graphs and repositories for child entities, and what a narrow, aggregate-specific repository interface looks like with DI registration.
A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.
In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:
IQueryable<T> GetAll() leaks EF semantics to callers.Save() per repository breaks the unit of work.A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.
"The Repository pattern, as Fowler and Evans describe it, gives the domain an in-memory collection illusion over persistence. Code that places an order says
orders.GetAsync(orderId, ct)andorders.Add(order), and doesn't care whether that's SQL Server, Cosmos DB or a test double. The key DDD rule is one repository per aggregate root: there's anIOrderRepository, but noIOrderLineRepository, because order lines are only changed through theOrder, which enforces rules like 'you can't add lines to a submitted order'. That's the difference from a DAO or table gateway, which mirrors tables: one class per table with Insert, Update, Delete and Select.In .NET the twist is that EF Core's
DbContextalready implements both Repository and Unit of Work. ADbSet<Order>is a collection of orders, andSaveChangesAsynccommits every change tracked in the request as one transaction. So when a team wraps it in a genericIRepository<T>withGetAll,GetById,Update,DeleteandSave, they usually make things worse.IQueryable<T> GetAll()leaks EF Core: callers write LINQ that may not translate, and the 'abstraction' still depends on EF behaviour.Update(entity)callsDbSet.Update, which marks every column as modified. ASave()on each repository means two repositories in one use case commit separately, so you've lost the unit of work. And because the generic repository works for any type, someone createsIRepository<OrderLine>and bypasses the aggregate.The mistake I see is treating the repository as a required layer rather than a tool for protecting a domain model. When I use one, it's specific:
IOrderRepositorywithGetAsync,Add, maybeGetByCustomerAsync, all taking aCancellationToken, returning aggregates, and never callingSaveChanges. That belongs to the use case or a unit of work. Reads for screens skip it and project straight from theDbContext. A repository should earn its place by protecting aggregates, not by hiding EF Core for the sake of hiding it."
DbContext| Repository | DAO / table gateway | DbContext directly |
|
|---|---|---|---|
| Unit | Aggregate root | Table | Whole model |
| Language | Domain (GetAsync(orderId)) |
CRUD (Insert, UpdateRow) |
LINQ over DbSet<T> |
| Commits | No, the unit of work does | Often each call | SaveChangesAsync |
| Hides EF Core | Yes | Yes | No |
| Best for | Rich domain with invariants | Legacy ADO.NET, stored procs | CRUD and query endpoints |
| Member | Problem |
|---|---|
IQueryable<T> GetAll() |
Leaks provider behaviour; callers can write untranslatable LINQ or forget AsNoTracking |
Update(T entity) |
DbSet.Update marks every property modified and attaches the whole graph |
Save() per repository |
Two repositories commit in two transactions: no unit of work |
IRepository<OrderLine> |
Children change outside their aggregate root, skipping invariants |
GetById(object id) |
Loses the strong ID type and the aggregate's Include/owned loading rules |
null), never IQueryable.SaveChanges: the use case commits once, through the DbContext or an IUnitOfWork.DbContext.A claims service had a generic Repository<T> with Save() on each instance. Approving a claim saved the claim, then saved a payment through a second repository; when the second save failed on a constraint, about 0.4% of approved claims had no payment for several weeks. Replacing it with IClaimRepository, one SaveChangesAsync per use case, and payments created inside the claim aggregate removed the partial writes and deleted about 600 lines of pass-through code.
Checks whether the candidate knows the pattern's real intent (aggregate-level persistence abstraction) and can explain why a generic repository over EF Core usually hurts.
Green flags
DbContext/DbSet already implement Repository and Unit of Work.IQueryable, Update() marking all columns, Save() per repository.SaveChanges out of the repository.Red flags
SaveChanges.Fowler (Patterns of Enterprise Application Architecture, 2002) defines a repository as mediating between the domain and data mapping layers "using a collection-like interface for accessing domain objects". Evans (Domain-Driven Design, 2003) narrows it: provide repositories only for aggregate roots that need direct access, so every change goes through the root that guards the invariants.
Application service / handler
| orders.GetAsync(id) unitOfWork.SaveChangesAsync()
v |
IOrderRepository <----- domain owns the interface (DIP)
^
| implements
EfOrderRepository --> ShopDbContext.Orders (DbSet<Order>) --> SQL Server
|
change tracker (unit of work)
The interface lives with the domain or application layer; the EF Core implementation lives in infrastructure. That's the Dependency Inversion Principle applied to persistence.
OrdersGateway.Insert(...)).Order includes its lines because the aggregate is the consistency boundary.| Pattern | EF Core implementation |
|---|---|
| Repository | DbSet<T>: Add, Remove, FindAsync, LINQ |
| Unit of Work | Change tracker + SaveChangesAsync (one transaction by default) |
| Identity Map | The change tracker returns the same instance for the same key in one context |
| Data Mapper | Model configuration maps classes to tables |
So the question is never "do I need a repository to use EF Core?" but "does an extra abstraction protect something?"
IQueryable. GetAll() returns a query the caller extends. Behaviour depends on the provider (translation, client evaluation, tracking), so the abstraction hides nothing.Update() semantics. DbSet.Update sets every property's state to Modified and attaches the graph; tracked entities don't need it at all, because the change tracker already detected changes.Save(). Breaks the unit of work and creates partial writes.IRepository<OrderLine> lets code insert lines into a submitted order.GetAll().Where(...) in services, so query logic spreads anyway.GetAsync(OrderId), GetOpenForCustomerAsync(CustomerId), Add(Order).Update: load, call domain methods, commit.Remove(Order) only if the domain really deletes.Include), since partial aggregates break invariants.A repository adds one interface and one class per aggregate, plus an interface dispatch per call (nanoseconds; irrelevant next to a database round trip). The real cost is maintenance and the temptation to route every read through it. Reads for screens and reports should project directly with Select and AsNoTracking.
Repository<T> with Save(), use two in one use case, make the second save fail, and look at the partial data.DbSet.Update on a tracked entity after changing one property and compare the generated UPDATE (with LogTo) to just calling SaveChangesAsync.IOrderRepository and a single SaveChangesAsync; confirm one transaction in SQL Profiler or Extended Events.DbContext directly and compare its SQL to GetAll().ToList() then mapping.An aggregate-specific repository, a unit of work owned by the use case, and the generic repository it replaces.
namespace Shop.Orders;
public enum OrderStatus { Draft, Submitted, Cancelled }
public sealed class Order
{
private readonly List<OrderLine> _lines = [];
private Order() { } // for EF Core materialisation
public Order(Guid customerId)
{
Id = Guid.CreateVersion7(); // sortable ids index well in SQL Server
CustomerId = customerId;
Status = OrderStatus.Draft;
}
public Guid Id { get; private set; }
public Guid CustomerId { get; private set; }
public OrderStatus Status { get; private set; }
public IReadOnlyList<OrderLine> Lines => _lines;
// Invariants live on the aggregate root, so lines can't be changed behind its back
public void AddLine(string sku, int quantity, decimal unitPrice)
{
if (Status != OrderStatus.Draft) throw new InvalidOperationException("Only draft orders can change.");
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
_lines.Add(new OrderLine(sku, quantity, unitPrice));
}
public void Submit()
{
if (_lines.Count == 0) throw new InvalidOperationException("An order needs at least one line.");
Status = OrderStatus.Submitted;
}
}
public sealed class OrderLine(string sku, int quantity, decimal unitPrice)
{
public string Sku { get; private set; } = sku;
public int Quantity { get; private set; } = quantity;
public decimal UnitPrice { get; private set; } = unitPrice;
}
// Narrow, domain-named, no SaveChanges and no IQueryable
public interface IOrderRepository
{
Task<Order?> GetAsync(Guid id, CancellationToken ct);
void Add(Order order);
}
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
namespace Shop.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Shop.Orders;
public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options), IUnitOfWork
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder modelBuilder) =>
modelBuilder.Entity<Order>(b =>
{
b.OwnsMany(o => o.Lines, l => l.Property(x => x.UnitPrice).HasPrecision(18, 2)); // owned: loaded with the root
b.Navigation(o => o.Lines).HasField("_lines");
});
}
internal sealed class EfOrderRepository(ShopDbContext db) : IOrderRepository
{
public Task<Order?> GetAsync(Guid id, CancellationToken ct) =>
db.Orders.SingleOrDefaultAsync(o => o.Id == id, ct); // owned lines come with the aggregate
public void Add(Order order) => db.Orders.Add(order);
}
// The use case commits once, so every change in it is one transaction
public sealed class SubmitOrderHandler(IOrderRepository orders, IUnitOfWork unitOfWork)
{
public async Task HandleAsync(Guid orderId, CancellationToken ct)
{
var order = await orders.GetAsync(orderId, ct) ?? throw new KeyNotFoundException($"Order {orderId} not found.");
order.Submit(); // no Update() call: the change tracker saw the change
await unitOfWork.SaveChangesAsync(ct);
}
}
// Program.cs: everything scoped, so one DbContext is shared per request
builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
builder.Services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ShopDbContext>());
builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();
builder.Services.AddScoped<SubmitOrderHandler>();
// The anti-pattern this replaces:
// public interface IRepository<T> where T : class
// {
// IQueryable<T> GetAll(); // leaks EF Core to every caller
// Task<T?> GetByIdAsync(object id, CancellationToken ct);
// void Update(T entity); // DbSet.Update marks every column modified
// Task SaveAsync(CancellationToken ct); // each repository commits separately: no unit of work
// }
IRepository<T> for every entity over EF Core. Why it is wrong: It re-implements DbSet<T> with less power and invites repositories for child entities that bypass aggregate rules. Instead: Use DbContext directly, or write aggregate-specific repositories.IQueryable<T> from the repository. Why it is wrong: Callers depend on EF Core translation and tracking anyway, so the abstraction hides nothing and query logic spreads. Instead: Return materialised aggregates, or accept a specification.SaveChanges inside each repository method. Why it is wrong: Two repositories in one use case commit in separate transactions, causing partial writes. Instead: Commit once per use case through the DbContext or an IUnitOfWork.repository.Update(entity) after modifying a tracked entity. Why it is wrong: DbSet.Update marks every column modified and attaches the whole graph; the change tracker already saw the change. Instead: Load, call domain methods, SaveChangesAsync.DbContext with Select and AsNoTracking.DbContext (a captive dependency) shared across requests and threads. Instead: Register it scoped.I start from "DbContext is already a repository and a unit of work" and add a repository only where it protects something: a rich aggregate with invariants, a domain layer that must not reference EF Core, or a persistence technology that may genuinely change. For CRUD screens and queries, a repository is a pass-through I'd rather not maintain.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
DbContext directly in handlers |
CRUD, queries, small services | EF Core in the application layer | Rich aggregates that must be loaded whole |
| Aggregate-specific repository | DDD domain with invariants | One interface + class per aggregate | Pure CRUD |
Generic IRepository<T> |
Rarely; maybe a non-EF store with uniform CRUD | Leaky, breaks UoW, invites child repositories | Over EF Core |
| Repository + specifications | Many filter combinations on one aggregate | Specification infrastructure | Few, stable queries |
I measure the value by what changes when requirements change: if adding a query means touching an interface, an implementation and a test double with no new behaviour, the layer isn't paying for itself.
A specification wraps one business rule ("in stock", "price below X") in an object that exposes it as an Expression<Func<T,bool>>. Because it's an expression tree, EF Core translates it to SQL; compile it once and the same rule also works in memory (IsSatisfiedBy).
Rules compose with And/Or/Not, built from Expression.AndAlso/OrElse/Not plus an ExpressionVisitor that replaces parameters so both sides share one lambda parameter.
That replaces a repository with dozens of GetProductsByXAndY methods with one ListAsync(spec) and small, named, testable rules. Ardalis.Specification packages this with ordering, includes and paging.
The trap: a spec typed as Func<T,bool> binds to Enumerable.Where, so EF loads the whole table and filters in memory. The trade-off is reusable rules against another abstraction to learn.
ISP says clients should not be forced to depend on methods they do not use. A fat interface such as IOrderService with 25 members couples every consumer to all of them, makes test doubles painful and pushes implementers to throw NotImplementedException. Split interfaces by what clients need (role interfaces): IOrderReader for queries, IOrderWriter for commands, IClock instead of a giant IUtilities. The BCL does this well (IReadOnlyCollection<T> versus ICollection<T>, IAsyncDisposable). Do not go to the extreme of one interface per method; group members that the same client uses together.
You register the open types, services.AddScoped(typeof(IRepository<>), typeof(Repository<>)), and when someone asks for IRepository<Order> the container closes the implementation with MakeGenericType and builds it, caching that plan. An exact closed registration for IRepository<Order> wins over the open one, while IEnumerable<IRepository<Order>> returns both. Lifetimes are per closed type. Microsoft DI has no decorator support, so I use Scrutor's Decorate for open generics or write it by hand. ValidateOnBuild cannot check open generics, so I add tests that resolve real closed types.
I decide by what the abstraction protects, not by habit. DbContext is already a repository and unit of work, so a wrapper has to earn its place.
DbContext with Select and AsNoTracking. Never return IQueryable from a repository.ExecuteUpdateAsync/ExecuteDeleteAsync bypass the change tracker and run at once, so they belong behind an intention-revealing method and need an explicit transaction to be atomic with SaveChanges.My answer flips for pure CRUD (skip repositories) or for Dapper, stored procedures or a second store (repositories hide them). The trade-off is domain protection against a layer that only renames EF Core.
Unit of Work records every change made during one business operation and commits them together or not at all.
In EF Core, DbContext is the unit of work. The change tracker records added, modified and deleted entities. One SaveChangesAsync sends them all in a single implicit transaction. That's why every repository in a request must share the same scoped DbContext: separate contexts mean separate commits.
You need an explicit transaction (Database.BeginTransactionAsync) when one operation spans several SaveChanges calls, ExecuteUpdate/ExecuteDelete (which run immediately and skip the change tracker) or raw SQL. With EnableRetryOnFailure, wrap that transaction in CreateExecutionStrategy().ExecuteAsync, and make the block safe to re-run.
The trade-off: one context per request gives you atomic commits, but a long-lived context grows its change tracker and holds stale data.
Last updated 18 Nov 2026.