Architecture decision on wrapping EF Core in repositories: testing with mocks vs EF in-memory/SQLite vs Testcontainers SQL Server, aggregate repositories for the write side vs direct DbContext projections for reads, leaky IQueryable, EF Core 10 ExecuteUpdate/ExecuteDelete (non-expression setter lambda) bypassing the change tracker, multiple persistence stores, team skill and when the decision flips, recorded as an ADR.
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.
"I'd reframe the argument first. Nobody disputes that EF Core works without repositories:
DbSet<T>is a repository andSaveChangesis a unit of work. The question is whether an extra layer protects something worth protecting. I look at three things. First, the domain: if we have aggregates with invariants, like an order that can't change after submission, a repository per aggregate root makes sure it's always loaded whole and changed through the root. Second, persistence variety: if some aggregates live in SQL Server, some come from a stored procedure through Dapper, and one is in Cosmos DB, a repository hides that. Third, the read side: screens and reports should project straight from theDbContextwithSelectandAsNoTracking. Routing them through repositories over-fetches and adds methods for every screen.I don't accept 'testability' on its own. Mocking
IOrderRepositoryonly proves the handler calls the mock; the bugs we actually ship are untranslatable LINQ, missing indexes, unique-constraint violations and transaction mistakes. The EF in-memory provider doesn't catch those either, because it has no SQL, no constraints and no real transactions. So I test persistence against SQL Server in Testcontainers whatever we decide, and domain logic in plain unit tests on the aggregate. For example, at [company] we [had a generic repository over EF Core with mocked tests], and [a unique-index violation and an untranslatable query both reached production despite 90%+ coverage]. I [moved the data tests to Testcontainers, kept repositories only for the three aggregates with real invariants, and let queries use the DbContext], and [production data bugs dropped from about [n] a quarter to [n]].EF Core 10 adds one wrinkle:
ExecuteUpdateAsyncandExecuteDeleteAsyncrun SQL immediately, bypass the change tracker and aren't part ofSaveChanges. EF Core 10 also lets you pass a regular lambda for the setters, so conditional updates are easy to write. I put those behind intention-revealing repository methods likeExpireDraftsOlderThanAsync, and wrap them in an explicit transaction when they must commit with other changes. The mistake I see is either extreme: a generic repository for every table, or EF queries scattered through controllers. I'd write the decision as an ADR that says which aggregates get repositories, what reads do instead, and what would make us change our minds."
| Situation | Repositories? | Why |
|---|---|---|
| CRUD admin service, thin rules | No | Pass-through layer; use DbContext in handlers |
| Rich aggregates with invariants | Yes, per aggregate root | Load whole, change through the root |
| Mixed stores (EF + Dapper/stored procs + Cosmos) | Yes | Hides the technology per aggregate |
| Read models, reports, search | No | Project from DbContext or SQL views |
| Domain project must not reference EF Core | Yes (interface in domain) | Dependency inversion |
| Team new to EF Core, scattered queries | Maybe, as a seam | But fix with conventions and review first |
| Approach | Catches | Misses | Speed |
|---|---|---|---|
Mock IOrderRepository |
Handler orchestration | All persistence bugs | Fastest |
| EF in-memory provider | Basic mapping | Translation, constraints, transactions, SQL nulls/collation | Fast |
| SQLite in-memory | Some SQL, constraints | SQL Server-specific SQL, rowversion, types |
Fast |
| Testcontainers SQL Server | Real translation, constraints, transactions | Little | ~5–10 s container start, then ms per test |
ExecuteUpdate/ExecuteDelete and the unit of workSaveChangesAsync |
ExecuteUpdateAsync/ExecuteDeleteAsync |
|
|---|---|---|
| When SQL runs | On commit | Immediately |
| Change tracker | Used | Bypassed (tracked entities go stale) |
| Domain methods/invariants | Run | Skipped |
| Atomic with other changes | Yes | Only inside an explicit transaction |
| Good for | Aggregate changes | Bulk set-based operations (expire, archive, purge) |
In an orders service at about 400 requests a second, moving read endpoints off a generic repository to Select projections with AsNoTracking cut p95 on the order list from about 180 ms to 45 ms and allocations per request by roughly 70%, because full aggregates were no longer loaded and tracked just to map them to DTOs. The write side kept four aggregate repositories, tested against Testcontainers SQL Server in about 40 seconds of CI time.
Checks architectural judgement: whether the candidate can weigh domain protection, testing reality and EF Core behaviour, and make a reversible, documented decision rather than a dogmatic one.
Green flags
ExecuteUpdate/ExecuteDelete bypass the change tracker and commit immediately.Red flags
IQueryable. WRITE SIDE READ SIDE
Endpoint -> Handler -> IOrderRepository Endpoint -> Query handler
| (aggregate root) |
v v
Order.Submit() (invariants) db.Orders.AsNoTracking()
| .Select(o => new OrderSummaryDto(...))
v |
unitOfWork.SaveChangesAsync() v
\____________ ShopDbContext ________________/
|
SQL Server
The split mirrors light CQRS: writes go through aggregates (where the repository earns its place), reads go straight to the shape the screen needs.
ExecuteUpdate/ExecuteDelete aren't supported.rowversion, different decimal handling).So "repositories make it testable" usually means "repositories make it mockable", which isn't the same thing.
A repository per aggregate root enforces two things: the aggregate is loaded completely (owned types or Include), and children are never changed directly. If your model has no invariants worth guarding, there's nothing for the repository to protect.
IQueryableReturning IQueryable<T> couples callers to EF translation rules, tracking behaviour and deferred execution (a query enumerated after the context is disposed throws). It also means query logic lives in every caller. Options instead: specific methods, a specification parameter, or a separate query side that is allowed to use DbContext.
ExecuteUpdateAsync/ExecuteDeleteAsync (EF Core 7+) translate to a single UPDATE/DELETE. EF Core 10 changed the setter parameter from Expression<Func<...>> to a regular Func<...>, so you can write if statements inside the setter block instead of building expression trees (a low-impact breaking change for code that built setter expressions by hand). EF Core 10 also supports ExecuteUpdate on JSON-mapped columns. Points that matter for patterns:
SaveChanges interceptors (auditing, soft delete, outbox).I expose them as named repository methods (ArchiveCompletedBeforeAsync) so the bypass is visible and reviewed.
| Trigger | Change |
|---|---|
| Domain grows real invariants | Introduce repositories for those aggregates only |
| Second store or Dapper for hot paths | Repository hides the technology |
| Service stays CRUD | Remove pass-through repositories |
| Performance work needs raw SQL | Put it behind the repository or a query object |
An ADR records context, decision, consequences and reversal conditions. Architecture tests (NetArchTest or ArchUnitNET) enforce it, e.g. "the Domain project doesn't reference Microsoft.EntityFrameworkCore" or "only Infrastructure and Queries reference ShopDbContext".
Orders.ExternalReference and write a duplicate; check which test approach catches it.ExecuteUpdateAsync on it, then read the tracked entity's property; observe the stale value.ExecuteDeleteAsync and SaveChangesAsync in one transaction, throw between them, and verify nothing committed.Write side through an aggregate repository (including an EF Core 10 bulk method), read side projecting from DbContext, and a Testcontainers test.
namespace Shop.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Shop.Orders;
public interface IOrderRepository
{
Task<Order?> GetAsync(Guid id, CancellationToken ct);
void Add(Order order);
Task<int> ExpireDraftsOlderThanAsync(DateTimeOffset cutoff, bool notifyCustomers, CancellationToken ct);
}
internal sealed class EfOrderRepository(ShopDbContext db) : IOrderRepository
{
public Task<Order?> GetAsync(Guid id, CancellationToken ct) => db.Orders.SingleOrDefaultAsync(o => o.Id == id, ct);
public void Add(Order order) => db.Orders.Add(order);
// Set-based, runs immediately, bypasses the change tracker and SaveChanges interceptors.
// EF Core 10: the setter is a regular lambda, so conditional setters are plain C#.
public Task<int> ExpireDraftsOlderThanAsync(DateTimeOffset cutoff, bool notifyCustomers, CancellationToken ct) =>
db.Orders
.Where(o => o.Status == OrderStatus.Draft && o.CreatedAt < cutoff)
.ExecuteUpdateAsync(s =>
{
s.SetProperty(o => o.Status, OrderStatus.Cancelled);
if (notifyCustomers)
{
s.SetProperty(o => o.NotificationPending, true);
}
}, ct);
}
namespace Shop.Queries;
using Microsoft.EntityFrameworkCore;
using Shop.Infrastructure;
using Shop.Orders;
public sealed record OrderSummaryDto(Guid Id, OrderStatus Status, int LineCount, decimal Total);
// Read side: no repository, no tracking, only the columns the screen needs
public sealed class GetCustomerOrdersQuery(ShopDbContext db)
{
public Task<List<OrderSummaryDto>> ExecuteAsync(Guid customerId, CancellationToken ct) =>
db.Orders
.AsNoTracking()
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.CreatedAt)
.Select(o => new OrderSummaryDto(o.Id, o.Status, o.Lines.Count, o.Lines.Sum(l => l.Quantity * l.UnitPrice)))
.Take(50)
.ToListAsync(ct);
}
namespace Shop.Tests;
using Microsoft.EntityFrameworkCore;
using Shop.Infrastructure;
using Shop.Orders;
using Testcontainers.MsSql;
public class OrderPersistenceTests
{
[Fact]
public async Task Expiring_drafts_updates_only_old_drafts_in_real_sql_server()
{
var ct = CancellationToken.None;
await using var sql = new MsSqlBuilder().WithImage("mcr.microsoft.com/mssql/server:2022-latest").Build();
await sql.StartAsync(ct);
var options = new DbContextOptionsBuilder<ShopDbContext>().UseSqlServer(sql.GetConnectionString()).Options;
await using var db = new ShopDbContext(options);
await db.Database.MigrateAsync(ct); // real schema, real constraints
var old = new Order(Guid.NewGuid(), createdAt: DateTimeOffset.UtcNow.AddDays(-10));
var fresh = new Order(Guid.NewGuid(), createdAt: DateTimeOffset.UtcNow);
db.Orders.AddRange(old, fresh);
await db.SaveChangesAsync(ct);
var repository = new EfOrderRepository(db);
var updated = await repository.ExpireDraftsOlderThanAsync(DateTimeOffset.UtcNow.AddDays(-7), notifyCustomers: false, ct);
Assert.Equal(1, updated);
db.ChangeTracker.Clear(); // tracked copies are stale after ExecuteUpdate
Assert.Equal(OrderStatus.Cancelled, (await db.Orders.SingleAsync(o => o.Id == old.Id, ct)).Status);
Assert.Equal(OrderStatus.Draft, (await db.Orders.SingleAsync(o => o.Id == fresh.Id, ct)).Status);
}
}
The Order here extends the earlier aggregate with CreatedAt and NotificationPending and a constructor overload Order(Guid customerId, DateTimeOffset createdAt).
ExecuteUpdate/ExecuteDelete. Instead: Testcontainers SQL Server (or SQLite only when the differences don't matter).IQueryable<T> from repositories to stay flexible. Why it is wrong: It leaks EF semantics and deferred execution, and query logic spreads to every caller. Instead: Specific methods, specifications, or a separate query side using DbContext.AsNoTracking().Select(...) projections on the read side.ExecuteUpdateAsync and assuming it's part of the next SaveChangesAsync. Why it is wrong: It commits immediately on its own and skips interceptors and domain rules. Instead: Use it for set-based work behind a named method, inside an explicit transaction when atomicity matters.The senior move is to separate the two arguments that usually get mixed together: domain protection (a good reason) and mockability (a weak one). I'll add repositories for aggregates that have invariants or live in a different store, keep the read side on DbContext projections, and spend the testing effort on Testcontainers where the real bugs are.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
DbContext everywhere |
CRUD services, small teams | EF Core in the application layer | Rich aggregates with invariants |
Repositories for aggregates + DbContext for reads |
Most business services | Some duplication of concepts | Pure CRUD |
| Repositories for everything | Multiple stores, strict domain purity | Pass-through code, slower change | Single EF Core store with simple rules |
Generic IRepository<T> |
Almost never over EF Core | Leaky, breaks UoW | Default choice |
I measure the outcome with escaped persistence bugs per quarter, CI time for data tests, and how many files a typical new query touches. If a new screen needs edits in an interface, an implementation and a fake, the abstraction is costing more than it saves.
IQueryable<T> is an IEnumerable<T> that also carries an expression tree and a provider. Queryable.Where takes an Expression<Func<T,bool>> and just wraps the expression, and when you enumerate, the provider, for example EF Core, translates the whole tree, typically into SQL. IEnumerable operators take delegates and run in memory. Which one you get depends on the static type of the variable, so storing a DbSet in an IEnumerable variable quietly moves every later Where into memory. AsEnumerable() does that on purpose. I keep IQueryable inside the data layer and return materialised results.
Over-engineering is complexity that today's requirements do not justify. I detect it through symptoms with numbers behind them: a one-field change touching many files, interfaces with one implementation, configuration options nobody sets, patterns like CQRS or event sourcing without the problems they solve, and microservices that always deploy together. I reverse it incrementally rather than with a rewrite: inline single-use abstractions, merge layers that only pass data through, consolidate services that share a release cycle, and delete unused options, each step behind tests. I also address why it happened, because otherwise it grows back.
I do not abstract when there is no second variant, no boundary to protect and no testing need, because an abstraction costs indirection, a name, a contract and cognitive load. Typical examples are an IOrderService with one implementation used by one controller, a generic repository over EF Core, or a wrapper around HttpClient or ILogger<T>, which are already abstractions. I do abstract at architecture boundaries (ports for payment vendors, email, storage) and where tests need a seam for something slow or non-deterministic. If an abstraction has had one implementation and one caller for a long time and is not at a boundary, I inline it.
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.
I choose patterns from the forces, not from a template: domain complexity and invariants, consistency needs, integrations, scale and the team.
Every service gets a cheap baseline: DbContext as the unit of work, DTOs at boundaries, validation, typed HttpClients with resilience, an outbox for integration events, and observability.
DbContext in handlers and projections for reads. No repositories, CQRS levels, mediator or domain services.Each extra pattern needs a named trigger. I record decisions as ADRs with reversal conditions and enforce them with architecture tests. The trade-off is fitting the design to today's problem against preparing for change that may never come.
How to tell it (STAR)
**S:** At [company], our orders API had a generic repository over EF Core and mocked data-access tests with over 90% coverage, yet a duplicate-key error hit [~2%] of checkouts and an untranslatable query broke search. **T:** I was asked to work out why tests didn't catch it and fix the approach, not just the bugs. **A:** I reproduced both bugs in a Testcontainers SQL Server test, showed the team that mocks never ran SQL, and proposed an ADR: repositories only for the [three] aggregates with real invariants, one `SaveChangesAsync` per use case, projections for reads, and Testcontainers in CI. **R:** Escaped data bugs went from about [n] a quarter to [n], order-list p95 fell from [180 ms] to [45 ms], and we deleted about [600] lines of pass-through code.
Last updated 18 Nov 2026.