📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your team is starting a new .NET 10 service on EF Core 10 and is split on whether to wrap DbContext in repositories. How do you decide? Cover testability (mocks, the in-memory provider, Testcontainers), aggregate boundaries, leaking IQueryable, ExecuteUpdate/ExecuteDelete, and the situations where your answer changes.

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.

Senior Architecture Advanced architecture design-patterns ef-core repository testcontainers testing

🎯 Key points

  • Decide by what the abstraction protects (aggregate invariants, domain purity, a second store), not by habit or 'testability' alone
  • Mocking repositories tests your mocks; EF in-memory provider ignores SQL semantics (transactions, constraints, translation); Testcontainers SQL Server tests the real thing
  • Common split: aggregate repositories on the write side; reads in dedicated query handlers that project from DbContext (Select + AsNoTracking), or from a separate read model when queries outgrow the write schema
  • Never return IQueryable from a repository; it leaks provider behaviour and spreads query logic
  • EF Core 10 ExecuteUpdateAsync/ExecuteDeleteAsync run immediately, bypass the change tracker and SaveChanges, and need an explicit transaction to be atomic with other changes; EF Core 10 accepts a regular (non-expression) setter lambda
  • Answer changes when: rich domain with invariants (add repositories), pure CRUD (skip), Dapper/stored procs or multiple stores (repository hides them), shared-kernel library constraints
  • Record the decision in an ADR with the conditions that would reverse it, and enforce with architecture tests (NetArchTest/ArchUnitNET)

⏱ 30-second answer

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.

  • Testability alone isn't a reason. Mocking repositories tests the mocks, and the EF in-memory provider ignores SQL semantics. I test persistence against SQL Server in Testcontainers either way.
  • Write side: repositories per aggregate root pay off when aggregates have invariants and must be loaded whole.
  • Read side: project straight from DbContext with Select and AsNoTracking. Never return IQueryable from a repository.
  • EF Core 10 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd reframe the argument first. Nobody disputes that EF Core works without repositories: DbSet<T> is a repository and SaveChanges is 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 the DbContext with Select and AsNoTracking. Routing them through repositories over-fetches and adds methods for every screen.

I don't accept 'testability' on its own. Mocking IOrderRepository only 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: ExecuteUpdateAsync and ExecuteDeleteAsync run SQL immediately, bypass the change tracker and aren't part of SaveChanges. 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 like ExpireDraftsOlderThanAsync, 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."


Decision matrix

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

Testing options

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 work

SaveChangesAsync 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)

Production example

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.

🔍 What the interviewer is checking

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

  • Separates domain protection from mockability.
  • Knows the limits of the EF in-memory provider and uses Testcontainers.
  • Splits write side (aggregate repositories) and read side (projections).
  • Knows ExecuteUpdate/ExecuteDelete bypass the change tracker and commit immediately.
  • Records the decision with reversal conditions.

Red flags

  • "Always use repositories" or "never use repositories" with no context.
  • Repositories that return IQueryable.
  • Relies on the in-memory provider for data-access tests.
  • No mention of aggregates or transactions.

📚 Learn in depth

1. What you're really deciding

          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.

2. The testability argument, examined

  • Mocks verify interactions, not persistence. A query that EF can't translate passes because the mock never runs it.
  • EF in-memory provider: Microsoft's own docs discourage it for testing data access. There's no SQL, no relational constraints, no real transactions, case-sensitive string comparison unlike default SQL Server collation, and ExecuteUpdate/ExecuteDelete aren't supported.
  • SQLite in-memory: closer, but different SQL dialect and types (no rowversion, different decimal handling).
  • Testcontainers SQL Server: the real engine in Docker. Start one container per test run, apply migrations once, and isolate tests with transactions rolled back or Respawn to reset data.

So "repositories make it testable" usually means "repositories make it mockable", which isn't the same thing.

3. Aggregates decide the shape

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.

4. Leaking IQueryable

Returning 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.

5. EF Core 10 bulk operations

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:

  • They don't go through the change tracker, so entities already loaded in the context keep stale values.
  • They skip domain logic and SaveChanges interceptors (auditing, soft delete, outbox).
  • Without an explicit transaction they commit on their own.

I expose them as named repository methods (ArchiveCompletedBeforeAsync) so the bypass is visible and reviewed.

6. When the answer changes

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

7. Making the decision stick

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".

Try it yourself

  1. Write the same persistence test three ways (mock, EF in-memory, Testcontainers) for a query that uses a method EF can't translate; see which one fails.
  2. Add a unique index on Orders.ExternalReference and write a duplicate; check which test approach catches it.
  3. Load an order, run ExecuteUpdateAsync on it, then read the tracked entity's property; observe the stale value.
  4. Wrap an ExecuteDeleteAsync and SaveChangesAsync in one transaction, throw between them, and verify nothing committed.
  5. Write an ArchUnitNET or NetArchTest rule that fails if the Domain project references EF Core.

💻 Code

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).

⚠ Common mistakes

  • Mistake: Adding repositories "for testability" and testing with mocks only. Why it is wrong: Mocks never run SQL, so translation, constraint and transaction bugs reach production. Instead: Test persistence against SQL Server in Testcontainers and domain logic on the aggregate.
  • Mistake: Using the EF in-memory provider as a stand-in for SQL Server. Why it is wrong: It has no relational constraints, no real transactions, different string comparison, and doesn't support ExecuteUpdate/ExecuteDelete. Instead: Testcontainers SQL Server (or SQLite only when the differences don't matter).
  • Mistake: Returning 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.
  • Mistake: Routing reads through aggregate repositories and mapping to DTOs. Why it is wrong: It loads and tracks full aggregates to show three columns. Instead: AsNoTracking().Select(...) projections on the read side.
  • Mistake: Calling 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.
  • Mistake: Making the decision once for the whole codebase. Why it is wrong: CRUD areas and rich-domain areas have different needs. Instead: Decide per bounded context or aggregate, and record it in an ADR.
  • Mistake: Scattering EF queries through controllers because "no repositories". Why it is wrong: Query logic duplicates and is hard to review. Instead: Put queries in handlers or query objects with clear ownership.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says repositories shouldn't return IQueryable Why: Checks IQueryable vs IEnumerable and the cost of exposing IQueryable from a repository
    How to answer

    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.

  2. When: Candidate describes removing a generic repository that added no behaviour Why: Checks recognising and reversing over-engineered layers like pass-through repositories
    How to answer

    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.

  3. When: Candidate says the repository must earn its place Why: Checks judgement about premature abstraction
    How to answer

    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.

  4. When: Candidate says ExecuteUpdate bypasses the change tracker Why: Checks explicit transactions when ExecuteUpdate/ExecuteDelete mix with SaveChanges
    How to answer

    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.

  5. When: Candidate records the repository decision in an ADR with reversal conditions Why: Checks generalising the repository decision to choosing all enterprise patterns
    How to answer

    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.

    • CRUD admin service: vertical slices with DbContext in handlers and projections for reads. No repositories, CQRS levels, mediator or domain services.
    • Insurance claims: aggregates and repositories, domain services for cross-aggregate rules, light CQRS, outbox/inbox, and a saga for long-running claim workflows.

    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.

🛠 Real-world problems: how you handle them

Generic repository with mocked tests let a unique-index violation reach production
Situation
Orders API at [company] on Azure SQL in Australia East, about [400] requests a second at peak. Every entity had a generic `Repository<T>` with `Save()`, and data access was tested with mocked repositories (over 90% line coverage).
Signals
After a release, Application Insights showed a spike of `DbUpdateException` (SQL error 2601, duplicate key on `IX_Orders_ExternalReference`) on [~2%] of checkout requests; a second release threw `InvalidOperationException: could not be translated` on the order search endpoint. Neither showed up in CI.
Investigation
Exception telemetry pointed to two code paths. Reproduced both in a Testcontainers SQL Server test in minutes; the mocked tests never executed SQL. Reviewed the repository layer: `GetAll()` returned `IQueryable`, so the search endpoint built a LINQ query with a custom C# method EF couldn't translate, and the duplicate key came from a retry path that saved twice through two repositories.
Resolution
Immediate: hotfixed the search query to translatable LINQ and made the retry path check for an existing order by external reference. Real fix: moved data tests to Testcontainers SQL Server, kept repositories only for the [three] aggregates with invariants, removed `Save()` from repositories in favour of one `SaveChangesAsync` per use case, and moved read endpoints to `AsNoTracking` projections from `DbContext`.
Prevention
ADR documenting which aggregates get repositories and that reads use projections; NetArchTest rules banning `IQueryable` in repository interfaces; Testcontainers suite in CI on every PR; a code-review checklist item for new queries (translation, index, tracking).

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.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me