A new .NET project starts the way many do. Before the first endpoint exists, someone adds the data access layer: IRepository<T>, Repository<T>, IProductRepository, ProductRepository, IUnitOfWork, and UnitOfWork. Then the first feature arrives, and the repository method it needs looks like this:
public async Task<Product?> GetByIdAsync(
Guid id,
CancellationToken cancellationToken)
{
return await context.Products.FindAsync(
[id],
cancellationToken);
}
UnitOfWork.SaveChangesAsync calls context.SaveChangesAsync. AddAsync calls DbSet<T>.AddAsync. Delete calls Remove. Every method passes a call to Entity Framework Core unchanged, under a new name. Nothing is buggy, but it's worth asking before the next forty methods get written:
If your repository only forwards calls to DbContext, what problem is it actually solving?
Sometimes there's a good answer. This article covers both cases: where the Repository Pattern with EF Core is redundant, and where a repository earns its place. The previous post on Clean Architecture named generic repositories as one source of accidental complexity. This one goes deeper, with a working product API, PostgreSQL integration tests, and a refactoring plan.
The samples target .NET 10, EF Core 10.0.15, Npgsql 10.0.4, xUnit v3, and Testcontainers 4.17. I compiled all of them, and ran the tests against PostgreSQL 17, while preparing this article.
What the Repository Pattern Was Designed to Solve
Martin Fowler's Patterns of Enterprise Application Architecture (2002) defines a Repository as something that "mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." It sits on top of a data mapper, which in 2002 was often hand-written ADO.NET, and keeps SQL and mapping out of business code. Client code works with what feels like an in-memory set of objects.
Eric Evans' Domain-Driven Design (2003) narrowed the idea. Repositories exist for aggregate roots only. An aggregate is a cluster of objects changed as one unit, like an Order and its OrderLines (Fowler's summary). You get an IOrderRepository, never an IOrderLineRepository, and its methods speak the domain's language: GetPendingShipments(), not Query(predicate).
So the original goals were:
- Collection-like access to domain objects.
- Persistence abstraction that keeps storage details out of business logic.
- Domain-oriented queries named after business intent.
- Separation of concerns and, through it, testability with in-memory implementations.
- Aggregate boundaries: one repository per consistency boundary, not per table.
A CRUD service for every table isn't on that list. A Fowler/Evans repository is shaped by the domain. A generic IRepository<T> with GetById, GetAll, Add, Update, and Delete is shaped by the schema. They share a name, and most arguments about "the Repository Pattern" are really about the second one.
EF Core Already Does Much of This
EF Core is the data mapper a repository was meant to sit on, and it already includes much of the repository.
DbSet<T> gives you entity collection access (db.Products), query composition (LINQ operators combine into one SQL statement), add and remove operations, and entity tracking. FindAsync even checks the change tracker before querying.
DbContext tracks changes and turns them into INSERT, UPDATE, and DELETE statements on SaveChangesAsync. By default, if the provider supports transactions, all changes in one SaveChanges call are applied in a single transaction, and a failure rolls back the whole call (EF Core transactions). That's Fowler's Unit of Work, and Microsoft's guide on designing the persistence layer says directly that DbContext implements both patterns.
The fit isn't literal, though:
- There's a
DbSet<T>for every entity, including ones that should only be reached through an aggregate root. DbSet<T>exposesIQueryable<T>, so callers can write any query, including one that loads half an aggregate.DbContextis an EF Core type, so whoever depends on it depends on EF Core.
You need an explicit transaction (Database.BeginTransactionAsync) when one operation calls SaveChangesAsync more than once, when you mix it with ExecuteUpdateAsync, ExecuteDeleteAsync, or raw SQL (these run immediately, outside the change tracker), when you need a locking read like SELECT ... FOR UPDATE, or when you need a specific isolation level. If you enable a retrying execution strategy (EnableRetryOnFailure), EF Core rejects user-initiated transactions unless they run inside Database.CreateExecutionStrategy().ExecuteAsync(...), so the whole transaction can be replayed (connection resiliency). Scenario B below shows this.
| Concept | Classic Repository / Unit of Work | EF Core | Where the fit is loose |
|---|---|---|---|
| Collection-like access | IOrderRepository returns domain objects |
DbSet<Order> |
One DbSet per entity, not per aggregate |
| Query by criteria | Named methods or specifications | LINQ over IQueryable<T> |
Any query is allowed |
| Track changes | Registers new, dirty, removed objects | Change tracker | Automatic, easy to save more than intended |
| Commit | UnitOfWork.Commit() |
SaveChangesAsync() |
One call = one transaction |
| Persistence ignorance | Domain depends on an interface | Code depends on DbContext |
Callers depend on EF Core |
The Generic Repository Anti-Pattern
Here's the generic repository from the introduction, written carefully:
public interface IRepository<T>
where T : class
{
Task<T?> GetByIdAsync(
Guid id,
CancellationToken cancellationToken);
Task<List<T>> GetAllAsync(
CancellationToken cancellationToken);
Task AddAsync(
T entity,
CancellationToken cancellationToken);
void Update(T entity);
void Delete(T entity);
}
public class Repository<T>(CatalogDbContext context) : IRepository<T>
where T : class
{
protected DbSet<T> Set { get; } = context.Set<T>();
public async Task<T?> GetByIdAsync(Guid id, CancellationToken cancellationToken) =>
await Set.FindAsync([id], cancellationToken);
public Task<List<T>> GetAllAsync(CancellationToken cancellationToken) =>
Set.ToListAsync(cancellationToken);
public async Task AddAsync(T entity, CancellationToken cancellationToken) =>
await Set.AddAsync(entity, cancellationToken);
public void Update(T entity) => Set.Update(entity);
public void Delete(T entity) => Set.Remove(entity);
}
The problems show up as real features hit it:
- Entity key assumptions.
GetByIdAsync(Guid id)breaks on the firstintor composite key, and pushes the design towardobject id. GetAllAsyncis a trap. It loads a whole table, tracked. Once it exists, someone will call it and filter in memory.- Loss of query composition. A method returning
List<T>orThas already executed. You can't add a projection, a page size, orAsNoTrackingafterwards. - Generic abstractions multiply. Filtering adds
Find(Expression<Func<T, bool>>), then anincludesparameter, then ordering, paging, and tracking flags. The interface becomes a worse copy of LINQ. - EF Core leaks through anyway.
FindAsyncreturns tracked entities, though the interface doesn't say so.Updatemarks every property modified, so a one-column change becomes a full-row UPDATE (and on a tracked entity, the call isn't needed at all).AddAsyncwrapsDbSet.AddAsync, which the API docs say exists only for value generators that need the database, such as SQL Server HiLo. Otherwise,Addis correct. - Domain-specific queries don't fit. "Active products in a category, by name, 25 per page" ends up in
IProductRepository, which then holds the code that matters. - Duplicated persistence APIs.
DbSet<T>already has these five operations, with more capabilities.
What about returning IQueryable?
Adding IQueryable<T> Query() restores composition, but it changes what the repository is. The caller now writes the query: it only works if the provider can translate it, and Include, AsSplitQuery, and ToListAsync are EF Core methods. The repository no longer decides what gets loaded. It's a renamed DbSet<T>.
That's acceptable when the caller is already infrastructure (a read-model handler allowed to know EF Core), or when IQueryable<T> only passes between private helpers inside the repository. It weakens the boundary when the repository exists to keep EF Core out of application code or to enforce aggregate loading. A caller holding an IQueryable<Order> can skip Include(o => o.Lines). If you want those guarantees, return materialized results from intention-revealing methods. If you don't, injecting the DbContext is the more honest choice.
Real Example: Product API With a Generic Repository
Here's a realistic catalog feature: get a product, create a product. It uses Minimal APIs, EF Core with PostgreSQL, DTOs, and typed HTTP results. I've written it the way a careful team would.
public sealed class Product
{
public Guid Id { get; init; } = Guid.CreateVersion7();
public required string Sku { get; init; }
public required string Name { get; set; }
public decimal Price { get; set; }
public bool IsActive { get; set; } = true;
public Guid CategoryId { get; set; }
public Category Category { get; set; } = null!;
}
public sealed class Category
{
public Guid Id { get; init; } = Guid.CreateVersion7();
public required string Name { get; set; }
}
public sealed class CatalogDbContext(DbContextOptions<CatalogDbContext> options)
: DbContext(options)
{
public DbSet<Product> Products => Set<Product>();
public DbSet<Category> Categories => Set<Category>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>(product =>
{
product.Property(p => p.Id).ValueGeneratedNever();
product.HasIndex(p => p.Sku).IsUnique();
product.Property(p => p.Sku).HasMaxLength(64);
product.Property(p => p.Name).HasMaxLength(200);
product.Property(p => p.Price).HasPrecision(18, 2);
});
modelBuilder.Entity<Category>(category =>
{
category.Property(c => c.Id).ValueGeneratedNever();
category.Property(c => c.Name).HasMaxLength(100);
});
}
}
The contracts are records, separate from the entity:
public sealed record ProductDetails(
Guid Id,
string Sku,
string Name,
decimal Price,
string Category);
public sealed record CreateProductRequest(
string Sku,
string Name,
decimal Price,
Guid CategoryId);
FindAsync can't load Category, so the product repository adds what the feature needs:
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
public sealed class UnitOfWork(CatalogDbContext context) : IUnitOfWork
{
public Task<int> SaveChangesAsync(CancellationToken cancellationToken) =>
context.SaveChangesAsync(cancellationToken);
}
public interface IProductRepository : IRepository<Product>
{
Task<Product?> GetWithCategoryAsync(Guid id, CancellationToken cancellationToken);
Task<bool> SkuExistsAsync(string sku, CancellationToken cancellationToken);
}
public sealed class ProductRepository(CatalogDbContext context)
: Repository<Product>(context), IProductRepository
{
public Task<Product?> GetWithCategoryAsync(Guid id, CancellationToken cancellationToken) =>
Set.AsNoTracking()
.Include(p => p.Category)
.FirstOrDefaultAsync(p => p.Id == id, cancellationToken);
public Task<bool> SkuExistsAsync(string sku, CancellationToken cancellationToken) =>
Set.AnyAsync(p => p.Sku == sku, cancellationToken);
}
The service holds the logic and maps entities to DTOs:
public abstract record CreateProductResult
{
public sealed record Created(Guid Id) : CreateProductResult;
public sealed record Rejected(string Field, string Error) : CreateProductResult;
}
public sealed class ProductService(
IProductRepository products,
IRepository<Category> categories,
IUnitOfWork unitOfWork)
{
public async Task<ProductDetails?> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
var product = await products.GetWithCategoryAsync(id, cancellationToken);
if (product is null || !product.IsActive)
return null;
return new ProductDetails(
product.Id, product.Sku, product.Name, product.Price, product.Category.Name);
}
public async Task<CreateProductResult> CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken)
{
if (await categories.GetByIdAsync(request.CategoryId, cancellationToken) is null)
return new CreateProductResult.Rejected(nameof(request.CategoryId), "Category does not exist.");
if (await products.SkuExistsAsync(request.Sku, cancellationToken))
return new CreateProductResult.Rejected(nameof(request.Sku), "SKU is already in use.");
var product = new Product
{
Sku = request.Sku,
Name = request.Name,
Price = request.Price,
CategoryId = request.CategoryId
};
await products.AddAsync(product, cancellationToken);
await unitOfWork.SaveChangesAsync(cancellationToken);
return new CreateProductResult.Created(product.Id);
}
}
The endpoints translate results into HTTP:
public static class ProductEndpoints
{
public static IEndpointRouteBuilder MapProductEndpoints(this IEndpointRouteBuilder app)
{
var products = app.MapGroup("/api/products").WithTags("Products");
products.MapGet("/{id:guid}", GetById).WithName("GetProduct");
products.MapPost("/", Create);
return app;
}
private static async Task<Results<Ok<ProductDetails>, NotFound>> GetById(
Guid id,
ProductService service,
CancellationToken cancellationToken)
{
var product = await service.GetByIdAsync(id, cancellationToken);
return product is null
? TypedResults.NotFound()
: TypedResults.Ok(product);
}
private static async Task<Results<Created, ValidationProblem>> Create(
CreateProductRequest request,
ProductService service,
CancellationToken cancellationToken)
{
var result = await service.CreateAsync(request, cancellationToken);
return result switch
{
CreateProductResult.Created created =>
TypedResults.Created($"/api/products/{created.Id}"),
CreateProductResult.Rejected rejected =>
TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
[rejected.Field] = [rejected.Error]
}),
_ => throw new UnreachableException()
};
}
}
builder.Services.AddDbContext<CatalogDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Catalog")));
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped<ProductService>();
This is decent code. Here's how a create request flows through it:
POST /api/products
└─► ProductEndpoints.Create
└─► ProductService.CreateAsync
├─► IRepository<Category>.GetByIdAsync ─► Repository<Category> ─► DbSet<Category>.FindAsync
├─► IProductRepository.SkuExistsAsync ─► ProductRepository ─► DbSet<Product>.AnyAsync
├─► IProductRepository.AddAsync ─► Repository<Product> ─► DbSet<Product>.AddAsync
└─► IUnitOfWork.SaveChangesAsync ─► UnitOfWork ─► CatalogDbContext.SaveChangesAsync
◄── Created | ValidationProblem (translated from CreateProductResult)
Each repository call lands on exactly one EF Core call. The behavior that matters (what SQL runs, what gets tracked) is spread across three classes, and the service can't see any of it. Some costs only show up when you read every layer. The category check materializes and tracks a full Category just to test existence, because the generic interface has no AnyAsync. The read loads the whole product row and category, then keeps five fields, because repositories return entities. CreateProductResult exists only to cross the service boundary. Eight supporting types serve two operations.
The Same Feature Using DbContext Directly
The same feature as focused handlers. Contracts, routes, and HTTP behavior are identical.
public static class GetProduct
{
public static async Task<Results<Ok<ProductDetails>, NotFound>> Handle(
Guid id,
CatalogDbContext db,
CancellationToken cancellationToken)
{
var product = await db.Products
.AsNoTracking()
.Where(p => p.Id == id && p.IsActive)
.Select(p => new ProductDetails(
p.Id, p.Sku, p.Name, p.Price, p.Category.Name))
.FirstOrDefaultAsync(cancellationToken);
return product is null
? TypedResults.NotFound()
: TypedResults.Ok(product);
}
}
public static class CreateProduct
{
public static async Task<Results<Created, ValidationProblem>> Handle(
CreateProductRequest request,
CatalogDbContext db,
CancellationToken cancellationToken)
{
if (!await db.Categories.AnyAsync(c => c.Id == request.CategoryId, cancellationToken))
return Invalid(nameof(request.CategoryId), "Category does not exist.");
if (await db.Products.AnyAsync(p => p.Sku == request.Sku, cancellationToken))
return Invalid(nameof(request.Sku), "SKU is already in use.");
var product = new Product
{
Sku = request.Sku,
Name = request.Name,
Price = request.Price,
CategoryId = request.CategoryId
};
db.Products.Add(product);
await db.SaveChangesAsync(cancellationToken);
return TypedResults.Created($"/api/products/{product.Id}");
}
private static ValidationProblem Invalid(string field, string error) =>
TypedResults.ValidationProblem(new Dictionary<string, string[]> { [field] = [error] });
}
public static class ProductEndpoints
{
public static IEndpointRouteBuilder MapProductEndpoints(this IEndpointRouteBuilder app)
{
var products = app.MapGroup("/api/products").WithTags("Products");
products.MapGet("/{id:guid}", GetProduct.Handle).WithName("GetProduct");
products.MapPost("/", CreateProduct.Handle);
return app;
}
}
The only registration is AddDbContext, which makes the context scoped per request (the post on DbContext lifetimes explains why that matters).
POST /api/products
└─► CreateProduct.Handle
├─► db.Categories.AnyAsync (SELECT EXISTS ...)
├─► db.Products.AnyAsync (SELECT EXISTS ...)
├─► db.Products.Add
└─► db.SaveChangesAsync (INSERT, in its own transaction)
◄── Created | ValidationProblem
What you get:
- Less ceremony. Two handlers replace eight supporting types.
- Visible queries.
GetProduct.Handleshows the exact SQL shape: one join, five columns. - Feature cohesion. "Create a product" lives in one place, not in a service shared by fifteen operations.
- All of EF Core.
AsNoTracking, projections,AnyAsync,ExecuteUpdateAsync, and compiled queries need no new interface method. - Local optimization. Tuning a hot path changes one handler, not a contract other callers depend on.
Two honest notes. The SKU check races under concurrency: the unique index is the real guarantee, and production code should turn the resulting DbUpdateException into a validation error. The repository version has the same race. And AsNoTracking is technically redundant here, because projections without entity types aren't tracked (tracking docs). I keep it to signal intent.
The trade-off is real: application code now depends directly on EF Core. If your architecture requires persistence-independent application logic, enforced by project references, this approach breaks that rule. That's a decision to make on purpose.
What About Clean Architecture?
Clean Architecture's Dependency Rule says source-code dependencies point inward. The Domain holds entities and business rules and references nothing. The Application layer holds use cases and declares interfaces for what it needs. Infrastructure implements them with EF Core, HTTP clients, and brokers. Presentation is the delivery mechanism, such as Minimal API endpoints.
Source-code dependencies (compile time)
Presentation ──────────► Application ──────────► Domain
│ ▲
│ composition root │ implements IOrderRepository,
▼ │ IProductReadModel, ...
Infrastructure ───────────────┘
(EF Core, Npgsql, DbContext)
Where DbContext is allowed to appear, under each option
Option 1 Repository interfaces in Domain/Application DbContext only in Infrastructure
Option 2 Application-defined persistence abstraction DbContext only in Infrastructure
Option 3 Feature handlers in an outer layer DbContext in Presentation/Infrastructure
Option 4 Pragmatic: EF Core allowed in Application DbContext anywhere outside Domain
Injecting CatalogDbContext into a handler in the Application project makes Application depend on EF Core. Under a strict reading, that violates the rule. There are four reasonable responses:
- Repository interfaces in an inner layer. The textbook option. It's worth it when inner layers hold real business rules you want to test without a database. It costs the most when most operations are simple reads.
- Application-defined persistence abstractions. An
IProductReadModelwith query methods, or anIApplicationDbContextexposingDbSet<T>. Be honest about the second form:DbSet<T>is an EF Core type, so you get a test seam and a narrower surface, not persistence independence. - Feature handlers in an outer layer. A handler that only queries and returns a DTO doesn't need to be in Application. Put it in Presentation or Infrastructure, where EF Core is allowed. This keeps the rule intact and fits CQRS read paths well.
- Pragmatic architectures that allow EF Core. The team decides EF Core is a stable dependency for Application, while keeping the Domain clean. This departs from strict Clean Architecture and should be written down, for example in an architecture decision record. It fits teams that won't replace EF Core and prefer integration tests. It fits poorly when many teams need enforced boundaries.
The mistake isn't choosing option 4. It's choosing option 4 while telling yourself it's option 1.
When Repositories Actually Make Sense
Five situations where a repository protects something real, with honest costs.
Scenario A: Complex DDD aggregates
An Order owns its lines and enforces rules over all of them: at most 50 lines, quantities merge for the same product, and only drafts can change.
public enum OrderStatus { Draft, Submitted, Cancelled }
public sealed class Order
{
public const int MaxLines = 50;
private readonly List<OrderLine> _lines = [];
private Order() { } // for EF Core
public Order(Guid customerId)
{
Id = Guid.CreateVersion7();
CustomerId = customerId;
Status = OrderStatus.Draft;
}
public Guid Id { get; private set; }
public Guid CustomerId { get; private set; }
public OrderStatus Status { get; private set; }
public uint Version { get; private set; }
public IReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly();
public decimal Total => _lines.Sum(l => l.UnitPrice * l.Quantity);
public void AddLine(Guid productId, decimal unitPrice, int quantity)
{
EnsureDraft();
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
var existing = _lines.Find(l => l.ProductId == productId);
if (existing is not null)
{
existing.Increase(quantity);
return;
}
if (_lines.Count >= MaxLines)
throw new InvalidOperationException($"An order can have at most {MaxLines} lines.");
_lines.Add(new OrderLine(productId, unitPrice, quantity));
}
public void Submit()
{
EnsureDraft();
if (_lines.Count == 0)
throw new InvalidOperationException("An empty order cannot be submitted.");
Status = OrderStatus.Submitted;
}
private void EnsureDraft()
{
if (Status != OrderStatus.Draft)
throw new InvalidOperationException("Only draft orders can be changed.");
}
}
public sealed class OrderLine
{
private OrderLine() { } // for EF Core
internal OrderLine(Guid productId, decimal unitPrice, int quantity)
{
Id = Guid.CreateVersion7();
ProductId = productId;
UnitPrice = unitPrice;
Quantity = quantity;
}
public Guid Id { get; private set; }
public Guid ProductId { get; private set; }
public decimal UnitPrice { get; private set; }
public int Quantity { get; private set; }
internal void Increase(int quantity) => Quantity += quantity;
}
The repository speaks in aggregates: no Update, no GetAll, no IQueryable.
// Application layer
public interface IOrderRepository
{
Task<Order?> GetAsync(Guid orderId, CancellationToken cancellationToken);
void Add(Order order);
Task SaveChangesAsync(CancellationToken cancellationToken);
}
// Infrastructure layer
public sealed class OrderRepository(OrderingDbContext db) : IOrderRepository
{
public Task<Order?> GetAsync(Guid orderId, CancellationToken cancellationToken) =>
db.Orders
.Include(o => o.Lines)
.FirstOrDefaultAsync(o => o.Id == orderId, cancellationToken);
public void Add(Order order) => db.Orders.Add(order);
public Task SaveChangesAsync(CancellationToken cancellationToken) =>
db.SaveChangesAsync(cancellationToken);
}
public sealed record AddOrderLineRequest(Guid ProductId, decimal UnitPrice, int Quantity);
public static class AddOrderLine
{
public static async Task<Results<NoContent, NotFound, Conflict<string>>> Handle(
Guid orderId,
AddOrderLineRequest request,
IOrderRepository orders,
CancellationToken cancellationToken)
{
var order = await orders.GetAsync(orderId, cancellationToken);
if (order is null)
return TypedResults.NotFound();
try
{
order.AddLine(request.ProductId, request.UnitPrice, request.Quantity);
}
catch (InvalidOperationException ex)
{
return TypedResults.Conflict(ex.Message);
}
await orders.SaveChangesAsync(cancellationToken);
return TypedResults.NoContent();
}
}
(A real checkout would read the unit price from the catalog rather than trust the client. It's in the request here to keep the example short.)
Benefits: the interface documents how orders may be used, there's one loading path, and it always loads the whole aggregate. Order can be unit-tested without persistence. Costs: an interface and implementation per aggregate, plus a separate query path for reads like order history. That's light CQRS, and the team has to understand why both paths exist.
Scenario B: Encapsulating complex persistence queries
A transactional outbox processor must claim a batch of messages so parallel workers don't grab the same rows, then publish them, mark them processed, and commit, in a transaction that can be retried safely.
public interface IOutboxStore
{
Task<int> ProcessBatchAsync(
int batchSize,
Func<OutboxMessage, CancellationToken, Task> publish,
CancellationToken cancellationToken);
}
public sealed class PostgresOutboxStore(MessagingDbContext db, TimeProvider clock) : IOutboxStore
{
public async Task<int> ProcessBatchAsync(
int batchSize,
Func<OutboxMessage, CancellationToken, Task> publish,
CancellationToken cancellationToken)
{
var strategy = db.Database.CreateExecutionStrategy();
return await strategy.ExecuteAsync(async ct =>
{
db.ChangeTracker.Clear(); // a retry must not see entities from a failed attempt
await using var transaction = await db.Database.BeginTransactionAsync(ct);
// Row locks are held until commit; SKIP LOCKED lets parallel workers
// claim different rows instead of waiting on each other.
var batch = await db.OutboxMessages
.FromSql($"""
SELECT * FROM "OutboxMessages"
WHERE "ProcessedAt" IS NULL
ORDER BY "OccurredAt"
LIMIT {batchSize}
FOR UPDATE SKIP LOCKED
""")
.ToListAsync(ct);
foreach (var message in batch)
{
await publish(message, ct);
message.ProcessedAt = clock.GetUtcNow();
}
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
return batch.Count;
}, cancellationToken);
}
}
FromSql sends the interpolated batchSize as a parameter, not concatenated text (SQL queries). Delivery is at-least-once, so consumers must be idempotent.
Benefits: locking, the execution strategy, and PostgreSQL-specific SQL live in one named class. The worker that calls it is one line. Mistakes here cause duplicates or deadlocks, so this logic should exist exactly once. Costs: it's provider-specific by design. A SQL Server version would need different locking hints and fresh verification. It also needs integration tests against real PostgreSQL, because a mock can't tell you whether SKIP LOCKED works.
Scenario C: Persistence independence
"We might switch databases" is the most common reason given for repositories, and in most codebases the weakest. Moving from PostgreSQL to SQL Server means different collations and case sensitivity, NULL ordering, and date precision. Features like jsonb, arrays, xmin, SKIP LOCKED, and full-text search have to be re-engineered. You also need a new migration history, a data migration, and query tuning for a different planner. A repository interface removes none of that work, and EF Core already gives you the portability of LINQ until you use provider-specific features.
It is a real requirement for products where customers choose the database, for domain libraries shared with non-EF services, for data moving to a document store or an external API, and in regulated settings where the domain must compile without infrastructure. Benefits: the compiler enforces the boundary. Costs: every query needs an interface method, and there's a pull toward a lowest-common-denominator design. Pay it when the requirement is concrete, not speculative.
Scenario D: Multiple persistence sources
The product page needs catalog data from PostgreSQL and stock levels from a warehouse system that owns inventory:
public sealed record ProductAvailability(Guid ProductId, string Name, int? QuantityOnHand, bool StockKnown);
public interface IProductAvailabilityReader
{
Task<IReadOnlyList<ProductAvailability>> GetForCategoryAsync(
Guid categoryId,
CancellationToken cancellationToken);
}
public sealed class ProductAvailabilityReader(
CatalogDbContext db,
IWarehouseClient warehouse,
ILogger<ProductAvailabilityReader> logger) : IProductAvailabilityReader
{
public async Task<IReadOnlyList<ProductAvailability>> GetForCategoryAsync(
Guid categoryId,
CancellationToken cancellationToken)
{
var products = await db.Products
.AsNoTracking()
.Where(p => p.CategoryId == categoryId && p.IsActive)
.OrderBy(p => p.Name)
.Select(p => new { p.Id, p.Name })
.ToListAsync(cancellationToken);
IReadOnlyDictionary<Guid, int> stock;
try
{
stock = await warehouse.GetStockLevelsAsync(
products.Select(p => p.Id).ToArray(), cancellationToken);
}
catch (HttpRequestException ex)
{
// Degrade instead of failing the whole page.
logger.LogWarning(ex, "Warehouse unavailable; returning products without stock levels");
stock = new Dictionary<Guid, int>();
}
return products
.Select(p => stock.TryGetValue(p.Id, out var quantity)
? new ProductAvailability(p.Id, p.Name, quantity, StockKnown: true)
: new ProductAvailability(p.Id, p.Name, null, StockKnown: false))
.ToList();
}
}
Benefits: batching and fallback rules live in one place. If stock moves to a cache, only this class changes. Costs: it's easy to go too broad. A ProductRepository that quietly calls three systems in every method hides latency and failure modes. This is closer to a read model or gateway than a DDD repository, so name it that way.
Scenario E: Protecting domain invariants
Order.AddLine relies on _lines containing every line. Now picture a handler that loads the order directly:
var order = await db.Orders.FirstAsync(o => o.Id == orderId, cancellationToken);
order.AddLine(productId, unitPrice, quantity); // _lines is empty: no Include
Nothing fails. The limit check passes, the merge finds nothing, and EF Core inserts a duplicate line. The domain logic worked correctly on incomplete data. The invariant lives in the entity, but it relies on the aggregate being loaded whole. A repository with one loading path makes that structural. The mapping matters too:
public sealed class OrderingDbContext(DbContextOptions<OrderingDbContext> options)
: DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(order =>
{
order.Property(o => o.Id).ValueGeneratedNever();
order.Property(o => o.Version).IsRowVersion(); // maps to PostgreSQL xmin
order.HasMany(o => o.Lines)
.WithOne()
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade);
order.Navigation(o => o.Lines)
.HasField("_lines")
.UsePropertyAccessMode(PropertyAccessMode.Field);
});
modelBuilder.Entity<OrderLine>(line =>
{
line.Property(l => l.Id).ValueGeneratedNever();
line.Property(l => l.UnitPrice).HasPrecision(18, 2);
});
}
}
There's no DbSet<OrderLine>, and lines are reached through a backing field. Two details are easy to miss:
ValueGeneratedNever()on client-generated Guid keys is required. By convention, EF Core treats aGuidkey as generated. A newOrderLinewith a non-empty key, found in a tracked order's collection, is assumed to exist and gets an UPDATE. I checked: without that line, adding an item to a loaded order throwsDbUpdateConcurrencyException.- A row version only protects what touches the root. Npgsql maps a
uintrow version toxmin(Npgsql concurrency). But adding a line doesn't update theOrderrow, so concurrentAddLinecalls won't conflict unless every operation also modifies the root.
EF Core can also guarantee full loading without a repository: Navigation(o => o.Lines).AutoInclude() includes lines in every Order query unless a query calls IgnoreAutoIncludes() (eager loading), and owned collections (OwnsMany) always load with their owner. Consider both before adding an interface.
Benefits: consistency becomes part of the code's structure. Costs: nothing stops someone from injecting OrderingDbContext elsewhere, so add architecture tests. And keep rules in Order. A repository that collects business logic is a service with a misleading name.
Repository Pattern vs Specification Pattern
The Specification Pattern wraps a query criterion in a named object, so you don't end up with a dozen GetActiveProductsInCategory... variants. In EF Core, the simplest version is a named expression:
public static class ProductSpecifications
{
public static Expression<Func<Product, bool>> Sellable =>
p => p.IsActive && p.Price > 0;
public static Expression<Func<Product, bool>> InCategory(Guid categoryId) =>
p => p.CategoryId == categoryId;
}
var count = await db.Products
.Where(ProductSpecifications.Sellable)
.Where(ProductSpecifications.InCategory(categoryId))
.CountAsync(cancellationToken);
You get reusable criteria (change "sellable" once), composition (expressions combine into one WHERE), and separation of intent from execution: the specification says what qualifies, and the caller decides whether to count, page, or project.
Specifications complement repositories. A single ListAsync(ISpecification<Product> spec) method can serve many queries, with the specification carrying includes, ordering, and paging. Ardalis.Specification is a popular implementation. A library has its own costs: base classes and an evaluator to learn, query logic split across two places, and workarounds when a query doesn't fit the model.
Often, plain query extensions are enough:
public static class ProductQueryExtensions
{
public static IQueryable<Product> Sellable(this IQueryable<Product> products) =>
products.Where(p => p.IsActive && p.Price > 0);
public static IQueryable<Product> InCategory(this IQueryable<Product> products, Guid categoryId) =>
products.Where(p => p.CategoryId == categoryId);
}
C# 14 extension blocks offer the same idea with grouped members:
public static class ProductQueries
{
extension(IQueryable<Product> products)
{
public IQueryable<Product> SellableInCategory(Guid categoryId) =>
products.Where(p => p.IsActive && p.Price > 0 && p.CategoryId == categoryId);
}
}
Use specifications for many combinable criteria behind a repository boundary. Use extensions when you query DbContext directly and just want named filters. Neither is required.
Testing Without Repositories
"We need repositories so we can mock the database." Consider what each approach actually verifies.
Mocking IRepository<T> is fast, but it replaces the part most likely to be wrong. It won't catch a LINQ expression that doesn't translate, a missing Include, a missing unique index, lost decimal precision, or a case-sensitive filter. A mocked GetWithCategoryAsync keeps returning a category after someone deletes the real Include. Mocking DbSet<T> is worse, since LINQ to Objects accepts queries EF Core would reject, and the EF Core testing guidance discourages it.
SQLite runs real SQL, but it isn't PostgreSQL. It has no native decimal, and the provider documents limitations when comparing and ordering types like decimal and DateTimeOffset. Collation rules differ, jsonb, arrays, xmin, and SKIP LOCKED don't exist, and limited ALTER TABLE support changes how migrations behave. Passing on SQLite proves the code works on SQLite.
Real PostgreSQL catches what the others miss. Testcontainers makes it cheap: each run starts a disposable container. Here's a fixture and tests for GetProduct, using xUnit v3 and the Testcontainers PostgreSQL module:
using Catalog.Api.Data;
using Microsoft.EntityFrameworkCore;
using Testcontainers.PostgreSql;
using Xunit;
namespace Catalog.Tests;
public sealed class PostgresFixture : IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres =
new PostgreSqlBuilder("postgres:17").Build();
public async ValueTask InitializeAsync()
{
await _postgres.StartAsync();
await using var db = CreateCatalogContext();
await db.Database.EnsureCreatedAsync(); // or db.Database.MigrateAsync()
}
public CatalogDbContext CreateCatalogContext() =>
new(new DbContextOptionsBuilder<CatalogDbContext>()
.UseNpgsql(_postgres.GetConnectionString())
.Options);
public ValueTask DisposeAsync() => _postgres.DisposeAsync();
}
using Catalog.Api.Contracts;
using Catalog.Api.Data;
using Catalog.Api.Features.Products;
using Microsoft.AspNetCore.Http.HttpResults;
using Xunit;
namespace Catalog.Tests;
public sealed class GetProductTests(PostgresFixture database) : IClassFixture<PostgresFixture>
{
[Fact]
public async Task Returns_active_product_with_category_name()
{
var ct = TestContext.Current.CancellationToken;
var product = new Product
{
Sku = $"KB-{Guid.NewGuid():N}",
Name = "Mechanical keyboard",
Price = 129.90m,
Category = new Category { Name = "Keyboards" }
};
await using (var arrange = database.CreateCatalogContext())
{
arrange.Products.Add(product);
await arrange.SaveChangesAsync(ct);
}
await using var db = database.CreateCatalogContext();
var result = await GetProduct.Handle(product.Id, db, ct);
var ok = Assert.IsType<Ok<ProductDetails>>(result.Result);
Assert.Equal(
new ProductDetails(product.Id, product.Sku, "Mechanical keyboard", 129.90m, "Keyboards"),
ok.Value);
}
[Fact]
public async Task Returns_not_found_for_inactive_product()
{
var ct = TestContext.Current.CancellationToken;
var product = new Product
{
Sku = $"KB-{Guid.NewGuid():N}",
Name = "Discontinued keyboard",
Price = 59m,
IsActive = false,
Category = new Category { Name = "Keyboards" }
};
await using (var arrange = database.CreateCatalogContext())
{
arrange.Products.Add(product);
await arrange.SaveChangesAsync(ct);
}
await using var db = database.CreateCatalogContext();
var result = await GetProduct.Handle(product.Id, db, ct);
Assert.IsType<NotFound>(result.Result);
}
}
The project references xunit.v3, Testcontainers.PostgreSql, and Microsoft.NET.Test.Sdk, and like any xUnit v3 project it needs <OutputType>Exe</OutputType>. Use separate contexts to arrange and act. Otherwise the change tracker can answer the query and you're not testing what a real request sees. Unique SKUs let tests share one container. For routing and serialization, add WebApplicationFactory<Program> tests. In my runs, the container was ready in a few seconds, paid once per fixture.
Mocks are still right for logic that doesn't depend on the database. Test Order.AddLine with plain objects. Test the warehouse fallback with a fake IWarehouseClient that throws. A fake aggregate repository in handler tests is fine too, as long as the real one has integration tests. EF Core's docs on testing without the production database recommend the repository pattern for exactly that. The rule isn't "never mock." It's "don't mock what you're trying to verify."
Performance Considerations
There's no evidence that a repository layer itself is measurably slow. A virtual call is noise next to a database round trip, and I haven't benchmarked anything to claim otherwise. The real risk is indirect: a restrictive interface hides the right EF Core optimization, so the wrong one gets used (efficient querying).
- Change tracking and
AsNoTracking. Tracking snapshots every entity. AFindAsync-basedGetByIdAsyncalways tracks. - Projection.
Selectreads only the needed columns and tracks nothing. Entity-returning repositories load full rows first. - Query translation. EF Core throws on untranslatable expressions, except in the final projection. But a generic
Find(Func<T, bool>), as opposed toExpression<Func<T, bool>>, binds toEnumerable.Where, which loads the whole table and filters in memory. The compiler won't warn you. - N+1 queries.
GetAllAsync()on orders, thencustomers.GetByIdAsync(...)per order, looks harmless in a service and sends one query per row.
Pagination needs a page size, which GetAllAsync doesn't have. Offset paging slows as offsets grow, so the pagination docs recommend keyset paging:
var query = db.Products
.AsNoTracking()
.Sellable()
.InCategory(categoryId);
if (afterName is not null && afterId is { } lastId)
{
query = query.Where(p =>
string.Compare(p.Name, afterName) > 0 ||
(p.Name == afterName && p.Id.CompareTo(lastId) > 0));
}
var items = await query
.OrderBy(p => p.Name)
.ThenBy(p => p.Id)
.Take(PageSize + 1)
.Select(p => new ProductListItem(p.Id, p.Name, p.Price))
.ToListAsync(cancellationToken);
Taking PageSize + 1 rows reveals whether a next page exists without a COUNT.
Compiled queries skip EF Core's query cache lookup, which matters only on very hot paths (advanced performance). They're easy to use in a handler and have no home in a generic repository:
public static readonly Func<CatalogDbContext, Guid, CancellationToken, Task<ProductDetails?>> ById =
EF.CompileAsyncQuery((CatalogDbContext db, Guid id, CancellationToken ct) =>
db.Products
.AsNoTracking()
.Where(p => p.Id == id && p.IsActive)
.Select(p => new ProductDetails(p.Id, p.Sku, p.Name, p.Price, p.Category.Name))
.FirstOrDefault());
Batch operations with ExecuteUpdateAsync and ExecuteDeleteAsync run a single statement without loading anything (bulk operations):
await db.Products
.Where(p => p.CategoryId == categoryId && p.IsActive)
.ExecuteUpdateAsync(
setters => setters.SetProperty(p => p.IsActive, false),
cancellationToken);
await db.Products
.Where(p => !p.IsActive)
.ExecuteDeleteAsync(cancellationToken);
Doing the same through GetAllAsync + Update loads every row and sends one UPDATE per product. Bulk operations do run immediately, bypass the change tracker and SaveChanges interceptors, and skip domain methods. Use them for data operations, not for changes that must go through aggregate rules.
A Practical Decision Matrix
Treat this as a starting point for discussion, not a lookup table.
| Context | Direct DbContext fits when... | A repository fits when... | Typical starting point |
|---|---|---|---|
| Simple CRUD API | Logic fits in a handler | Rarely | Feature handlers with DbContext |
| Internal business app | Most screens are forms and lists | A few workflows have cross-entity invariants | Direct by default, aggregate repositories where needed |
| Complex DDD domain | Reads and reports | Aggregates enforce invariants, and the domain must not reference EF Core | Repositories for writes, projections for reads |
| Enterprise application | EF Core is an agreed dependency, enforced by architecture tests | Several teams need compile-time boundaries, or persistence independence is required | Decide per bounded context, document it |
| Reporting system | Almost always: projections, raw SQL, views | One façade over several stores | Direct queries |
| Microservice | Small service that owns its database | A rich aggregate sits at its core | Direct, repositories only around aggregates |
| Modular monolith | Inside a module, for its own tables | At module boundaries, via public contracts | Per-module DbContext, contracts between modules |
Does this code change data that must obey rules spanning several entities?
├── No ──► Is it a read that returns DTOs?
│ ├── Yes ──► Direct DbContext + projection (no repository)
│ └── No ──► Simple write: direct DbContext in a feature handler
└── Yes ─► Must the domain/application layer compile without EF Core?
├── Yes ──► Aggregate repository interface in an inner layer
└── No ──► Does more than one code path load this aggregate?
├── Yes ──► Aggregate repository (or AutoInclude/OwnsMany + architecture tests)
└── No ──► Load it fully in one handler; extract a repository when a second path appears
How to Refactor Away Unnecessary Repositories
Treat removal as a refactoring: small steps, tests first.
- Identify pass-through methods. Mark each repository method pass-through (one EF Core call) or meaningful (complex SQL, aggregate loading, multiple sources, invariants). Only pass-through methods are candidates.
- Map existing consumers. One caller is easy. Twelve is a project.
- Preserve transaction boundaries. A service that calls several repositories and then
IUnitOfWork.SaveChangesAsynconce defines a transaction. Keep exactly oneSaveChangesAsyncper operation, or use an explicit transaction. - Add characterization tests against real PostgreSQL: status codes, bodies, changed rows, edge cases. Record current behavior, odd parts included.
- Move queries into cohesive feature handlers without changing the public contract.
- Remove redundant abstractions incrementally, one feature per pull request.
- Validate database behavior by comparing SQL before and after (
LogToin a test run). - Measure maintainability: files touched per change, review time, tests broken by behavior-preserving refactors. If nothing improves, stop.
Before and after
// Before: service + generic repository + unit of work
public sealed class LegacyProductService(IRepository<Product> products, IUnitOfWork unitOfWork)
{
public async Task<bool> DeactivateAsync(Guid id, CancellationToken cancellationToken)
{
var product = await products.GetByIdAsync(id, cancellationToken);
if (product is null)
return false;
product.IsActive = false;
products.Update(product);
await unitOfWork.SaveChangesAsync(cancellationToken);
return true;
}
}
// After: one feature handler
public static class DeactivateProduct
{
public static async Task<Results<NoContent, NotFound>> Handle(
Guid id,
CatalogDbContext db,
CancellationToken cancellationToken)
{
var product = await db.Products.FindAsync([id], cancellationToken);
if (product is null)
return TypedResults.NotFound();
product.IsActive = false;
await db.SaveChangesAsync(cancellationToken);
return TypedResults.NoContent();
}
}
Before
POST /api/products/{id}/deactivate
└─► endpoint ─► LegacyProductService.DeactivateAsync
├─► IRepository<Product>.GetByIdAsync ─► Repository<Product> ─► FindAsync
├─► IRepository<Product>.Update ─► DbSet.Update (marks ALL columns modified)
└─► IUnitOfWork.SaveChangesAsync ─► SaveChangesAsync
SQL: UPDATE "Products" SET "CategoryId" = @p0, "IsActive" = @p1, "Name" = @p2, "Price" = @p3, "Sku" = @p4
WHERE "Id" = @p5
After
POST /api/products/{id}/deactivate
└─► DeactivateProduct.Handle
├─► db.Products.FindAsync
└─► db.SaveChangesAsync (change tracker detects the one changed property)
SQL: UPDATE "Products" SET "IsActive" = @p0 WHERE "Id" = @p1
Both statements come from logging real runs. Removing the layer also changed the SQL: the redundant Update was rewriting every column with values read moments earlier. That's usually an improvement, since it avoids lost updates when two requests change different columns. But a trigger or audit process that expects full-row writes would notice, which is why step 7 exists. Switching to ExecuteUpdateAsync would go further and skip interceptors and future domain methods. That's a different behavior, not just a faster one.
To avoid breaking domain invariants: don't flatten aggregate repositories into raw DbSet access unless every path still loads the whole aggregate (AutoInclude and owned types help). Move business checks into the entity before deleting the layer that held them, rather than copying them into handlers. Use architecture tests (NetArchTest or ArchUnitNET, for example) to forbid direct DbSet access where it matters.
Common Questions
Is DbContext already a Repository Pattern?
Mostly. DbSet<T> provides collection-like access and composition, and DbContext coordinates and commits changes. It doesn't restrict access to aggregate roots, hide EF Core, or limit queries to named operations. If you need those, add something on top.
Do I need Unit of Work with EF Core?
Usually not as a separate abstraction. SaveChangesAsync already commits all tracked changes in one transaction. An IUnitOfWork wrapper helps only when the application layer must not reference EF Core.
Is Generic Repository always an anti-pattern?
No, but it's a poor default over EF Core, because it duplicates DbSet<T> with fewer capabilities. As a small base class for aggregate repositories, it can be fine.
Can I use DbContext directly in Clean Architecture?
Not in Domain or Application under a strict Dependency Rule. You can use it in outer-layer handlers, or adopt a documented pragmatic variant. Just don't call it compliant when it isn't.
Should repositories return IQueryable?
Only if callers are allowed to write EF Core queries. If the repository exists to hide persistence or enforce aggregate loading, return materialized results.
How do I unit test without repositories?
Unit-test domain rules with plain objects. Integration-test handlers and queries against the real engine using Testcontainers. Fake only external systems.
Final Thoughts
EF Core already provides most of what the Repository and Unit of Work patterns were invented for. A generic repository on top usually copies that API with fewer features, hides the queries you'll need to tune, and adds types without adding decisions. Feature handlers using DbContext directly, verified by integration tests against real PostgreSQL, are often simpler and more honest.
Repositories still earn their place when they keep aggregates whole, give complex persistence one tested home, coordinate multiple sources, or keep EF Core out of inner layers by real requirement. Those repositories have few methods, domain names, and no GetAll.
Don't add a repository because a diagram tells you to. Add one when it protects a boundary that matters.
Decide on purpose, write down why, and revisit the decision when the code changes.
Do you use repositories with EF Core, or do you prefer working directly with DbContext?
References
- Martin Fowler, Repository and Unit of Work, Patterns of Enterprise Application Architecture (2002)
- Martin Fowler, DDD Aggregate
- Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software (2003)
- Microsoft Learn, Designing the infrastructure persistence layer
- Microsoft Learn, Using transactions (EF Core) and Connection resiliency
- Microsoft Learn, Tracking vs. no-tracking queries and Explicitly tracking entities
- Microsoft Learn, Efficient querying, Advanced performance topics, and Pagination
- Microsoft Learn, ExecuteUpdate and ExecuteDelete and SQL queries
- Microsoft Learn, Eager loading of related data, Owned entity types, and Backing fields
- Microsoft Learn, Choosing a testing strategy, Testing without your production database system, and SQLite provider limitations
- Npgsql, Concurrency tokens
- Testcontainers for .NET, PostgreSQL module
- Ardalis, Specification



