skip to content

In an ASP.NET Core app on EF Core 10, when does wrapping the DbContext in a repository add nothing, and when does it earn its place?

level: seniorimportance: should knowfreq 55%

answer

  1. DbContext is already a unit of work
  2. DbSet<T> is already a repository
  3. IQueryable leaks, IEnumerable cannot compose
  4. SaveChanges per repository breaks the unit
  5. stubbing query outputs in unit tests

basics

~20 s

A generic IRepository<T> over EF Core adds nothing when it forwards to DbSet<T>, returns IQueryable or calls SaveChanges itself. It earns its place when it hides specific, named queries for stubbing in tests or guards how an aggregate is loaded and saved.

solid answer

~50 s

EF Core's own documentation describes `DbContext` as a combination of the **Unit of Work** and **Repository** patterns: `DbSet<T>` is the collection-like repository, and `SaveChangesAsync` commits everything tracked in the scoped context. So a generic `IRepository<T>` with `GetById`, `GetAll`, `Add` and `Save` usually adds nothing. If it returns `IQueryable<T>`, EF Core still leaks to every caller. If it returns `IEnumerable<T>`, callers lose `Include`, `AsNoTracking`, projection and `ExecuteUpdateAsync`. If each repository calls `SaveChangesAsync`, a use case touching two of them commits twice. A repository earns its place when it is **specific**: named methods such as `GetWithVaccinationsAsync(patientId)` that encapsulate an aggregate's loading rules, or an interface the EF Core docs recommend for stubbing query **outputs** in unit tests, since `DbSet` queries cannot be mocked reliably. Even then, the queries behind it still need tests against the real database.

code

csharp · 19 lines
csharp
// Adds nothing: a pass-through that also commits on its own
public class Repository<T>(VetDbContext db) : IRepository<T> where T : class
{
    public IQueryable<T> Query() => db.Set<T>();
    public async Task AddAsync(T entity, CancellationToken ct)
    {
        db.Set<T>().Add(entity);
        await db.SaveChangesAsync(ct);
    }
}

// Earns its place: one aggregate, one loading rule, no IQueryable
public sealed class PatientRepository(VetDbContext db) : IPatientRepository
{
    public Task<Patient?> GetWithVaccinationsAsync(int id, CancellationToken ct) =>
        db.Patients
          .Include(p => p.Vaccinations)
          .SingleOrDefaultAsync(p => p.Id == id, ct);
}

go deeper

for a junior

Know that DbSet<T> already behaves like a repository and that SaveChangesAsync commits the tracked changes of one DbContext.

for a middle

Explain why returning IQueryable leaks EF Core while returning IEnumerable loses Include, projection and AsNoTracking, and who should call SaveChangesAsync.

for a senior

Argue from experience when a specific aggregate repository paid off, and how you tested the queries behind it against a real database.

for a principal

Set the team rule: direct DbContext in handlers, or specific repositories, given the architecture's dependency rules and the test strategy you can afford.

## What EF Core already gives you The XML documentation on EF Core's `DbContext` class says it plainly: a `DbContext` instance is a session with the database, and it "is a combination of the Unit Of Work and Repository patterns." - **Repository**: `DbSet<Patient>` behaves like an in-memory collection of patients. You `Add`, `Remove`, `Find`, and query it with LINQ. - **Unit of Work**: the change tracker records every change to tracked entities, and `SaveChangesAsync` writes them all in one transaction. - **Per request**: `AddDbContext<VetDbContext>` registers the context as **scoped** by default, so every handler and service resolved in one HTTP request shares one context and one unit of work. A repository layer is therefore not filling a gap; it is a wrapper around something that already has the pattern's shape. The question is whether the wrapper adds anything. ## When the wrapper adds nothing The pattern interviewers probe is the **generic repository**: `IRepository<T>` with `GetByIdAsync`, `GetAllAsync`, `Add`, `Update`, `Delete`, `SaveAsync`, implemented once over `DbSet<T>`. Its usual problems: 1. **Returning `IQueryable<T>`**: callers compose `Where`, `Include` and `Select` on it, so EF Core's query translation is still in the application layer. The abstraction hides nothing. 2. **Returning `IEnumerable<T>` or `List<T>`**: now callers cannot add a filter, an `Include`, `AsNoTracking` or a `Select` projection, so the repository grows a method per call site, or callers filter in memory after loading whole tables. 3. **Losing EF Core features**: `ExecuteUpdateAsync`, `ExecuteDeleteAsync`, split queries, compiled queries and raw SQL all need either the `IQueryable` or the context. 4. **Breaking the unit of work**: if `PatientRepository.SaveAsync` and `InvoiceRepository.SaveAsync` each call `SaveChangesAsync`, one use case commits twice. And because both share the scoped context, whichever repository saves first also commits the other's pending changes, which surprises everyone. 5. **The "swap the ORM" promise**: the interface is shaped by EF Core's semantics (tracking, lazy or explicit loading), so swapping is rarely as cheap as claimed. ## When it earns its place A repository is worth its cost when it is **specific to the domain**, not generic over every entity: - **Aggregate loading rules**: `IPatientRepository.GetWithVaccinationsAsync(id)` always applies the right `Include` calls, so no handler forgets to load the vaccination history before checking a booster rule. - **Unit testing without the database**: the EF Core testing guide recommends the repository pattern as the reliable way to test application code without a database. Mocking `DbSet<T>` **query** behaviour is not possible, because LINQ operators are static extension methods over `IQueryable`, and the in-memory provider is strongly discouraged as a database fake. A repository whose methods return `IEnumerable<T>` or `IAsyncEnumerable<T>` can be stubbed to return query **outputs** directly. - **Several stores behind one use case**: part of the data in PostgreSQL, part from an external records API. The cost is real: every testable query becomes a repository method, and those methods still need integration tests against the real database, because that is where translation and SQL behaviour live. ## A lighter way to name queries Many teams want the main benefit of a specific repository, named and reusable query logic, without a layer of interfaces. EF Core makes this cheap because queries are composable `IQueryable<T>` expressions: - An extension method such as `IQueryable<Patient> DueForBooster(this IQueryable<Patient> patients, DateOnly today)` names a filter once and can be combined with `AsNoTracking`, `Select` and `ToListAsync` by every handler. - Global query filters configured with `HasQueryFilter` keep rules such as "hide archived patients" out of individual queries altogether. This keeps full EF Core power in the handler, but it does not give a stubbable seam for unit tests; the handler is still tested against a real database. It is a good fit when the team has already decided to test that way. ## How to answer the trade-off | Choice | Adds | Costs | |---|---|---| | Handlers use `VetDbContext` directly | full EF Core power, no extra layer | handlers tested against a real database | | Generic `IRepository<T>` | little; a familiar shape | leaky or crippled queries, broken unit of work | | Specific aggregate repositories | encapsulated loading rules, stubbable outputs | a method per query, still needs integration tests | In a vertical-slice codebase, the common answer is the first row, with slices tested end to end against a real database. In a clean-architecture codebase where Application must not reference EF Core, specific repositories declared in Application and implemented in Infrastructure are the usual price of that rule. Either answer is defensible; the generic pass-through repository is the one that is hard to defend.

  • If a handler uses two specific repositories that share the scoped VetDbContext, who should call SaveChangesAsync?
    The handler, once, at the end of the use case, or a unit-of-work abstraction it calls. Because both repositories hold the same scoped context, one `SaveChangesAsync` commits both sets of changes in one transaction. Letting each repository save on its own splits the use case into two commits.
  • Why not test handlers that use VetDbContext directly with UseInMemoryDatabase?
    The EF Core docs strongly discourage the in-memory provider as a database fake: it is not relational, supports fewer queries, does not support transactions or raw SQL, and behaves differently from the real database. Tests pass against it and fail in production. Use the real database engine in tests, or put a stubbable repository in front of the queries.

  • Every EF Core app needs a generic repository to stay testable.
  • Returning IQueryable<T> from the repository keeps EF Core out of the handlers.
  • Each repository should call SaveChangesAsync after every Add.
  • You can mock DbSet<T> query results reliably with any mocking library.
  • The repository lets you swap EF Core for another ORM without touching handlers.