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

📚 Interview question

What is the Repository pattern? Explain its intent, how it differs from a DAO or a table gateway, why a generic IRepository<T> with GetAll, Update and Save over EF Core is often an anti-pattern, and what a good repository interface looks like in a .NET 10 service.

Repository pattern in .NET: intent (a collection-like abstraction over persistence for an aggregate root), repository vs DAO/table gateway, why a generic IRepository<T> over EF Core leaks IQueryable, breaks the unit of work with per-repository Save, encourages Update() on detached graphs and repositories for child entities, and what a narrow, aggregate-specific repository interface looks like with DI registration.

Intermediate Theory Intermediate dependency-injection design-patterns domain-driven-design ef-core generic-repository repository

🎯 Key points

  • Repository = collection-like abstraction over persistence for one aggregate root (Fowler/Evans), so the domain doesn't know about SQL or DbContext
  • One repository per aggregate root (IOrderRepository), not per table; child entities like OrderLine are loaded and saved through their root
  • A DAO/table gateway mirrors tables with CRUD per table; a repository speaks the domain's language (GetAsync(orderId), Add(order))
  • DbContext is already a repository (DbSet<T>) and unit of work (SaveChanges); a generic IRepository<T> over it adds a layer with no new behaviour
  • Generic repository smells: IQueryable<T> GetAll() leaks EF semantics (a leaky abstraction), Update() marks every column modified, Save() per repository breaks the unit of work
  • Good interface: few intention-revealing methods, returns aggregates or null, takes CancellationToken, no SaveChanges; accept a Specification instead of adding a method per filter combination
  • Register as scoped next to the scoped DbContext so all repositories in a request share one context
  • Read-heavy paths (screens, reports) bypass the repository and project from DbContext with Select and AsNoTracking, avoiding loading and tracking whole aggregates

⏱ 30-second answer

A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.

In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:

  • IQueryable<T> GetAll() leaks EF semantics to callers.
  • Save() per repository breaks the unit of work.
  • It invites repositories for child entities, which bypass the aggregate's rules.

A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.

🗣 Full answer (senior)

How I would answer this in an interview

"The Repository pattern, as Fowler and Evans describe it, gives the domain an in-memory collection illusion over persistence. Code that places an order says orders.GetAsync(orderId, ct) and orders.Add(order), and doesn't care whether that's SQL Server, Cosmos DB or a test double. The key DDD rule is one repository per aggregate root: there's an IOrderRepository, but no IOrderLineRepository, because order lines are only changed through the Order, which enforces rules like 'you can't add lines to a submitted order'. That's the difference from a DAO or table gateway, which mirrors tables: one class per table with Insert, Update, Delete and Select.

In .NET the twist is that EF Core's DbContext already implements both Repository and Unit of Work. A DbSet<Order> is a collection of orders, and SaveChangesAsync commits every change tracked in the request as one transaction. So when a team wraps it in a generic IRepository<T> with GetAll, GetById, Update, Delete and Save, they usually make things worse. IQueryable<T> GetAll() leaks EF Core: callers write LINQ that may not translate, and the 'abstraction' still depends on EF behaviour. Update(entity) calls DbSet.Update, which marks every column as modified. A Save() on each repository means two repositories in one use case commit separately, so you've lost the unit of work. And because the generic repository works for any type, someone creates IRepository<OrderLine> and bypasses the aggregate.

The mistake I see is treating the repository as a required layer rather than a tool for protecting a domain model. When I use one, it's specific: IOrderRepository with GetAsync, Add, maybe GetByCustomerAsync, all taking a CancellationToken, returning aggregates, and never calling SaveChanges. That belongs to the use case or a unit of work. Reads for screens skip it and project straight from the DbContext. A repository should earn its place by protecting aggregates, not by hiding EF Core for the sake of hiding it."


Repository vs DAO vs DbContext

Repository DAO / table gateway DbContext directly
Unit Aggregate root Table Whole model
Language Domain (GetAsync(orderId)) CRUD (Insert, UpdateRow) LINQ over DbSet<T>
Commits No, the unit of work does Often each call SaveChangesAsync
Hides EF Core Yes Yes No
Best for Rich domain with invariants Legacy ADO.NET, stored procs CRUD and query endpoints

Why the generic repository goes wrong

Member Problem
IQueryable<T> GetAll() Leaks provider behaviour; callers can write untranslatable LINQ or forget AsNoTracking
Update(T entity) DbSet.Update marks every property modified and attaches the whole graph
Save() per repository Two repositories commit in two transactions: no unit of work
IRepository<OrderLine> Children change outside their aggregate root, skipping invariants
GetById(object id) Loses the strong ID type and the aggregate's Include/owned loading rules

What a good repository looks like

  • One per aggregate root, named in domain terms.
  • A handful of intention-revealing methods; add one only when a use case needs it (Interface Segregation).
  • Returns aggregates (or null), never IQueryable.
  • No SaveChanges: the use case commits once, through the DbContext or an IUnitOfWork.
  • Scoped lifetime, sharing the request's DbContext.

Production example

A claims service had a generic Repository<T> with Save() on each instance. Approving a claim saved the claim, then saved a payment through a second repository; when the second save failed on a constraint, about 0.4% of approved claims had no payment for several weeks. Replacing it with IClaimRepository, one SaveChangesAsync per use case, and payments created inside the claim aggregate removed the partial writes and deleted about 600 lines of pass-through code.

🔍 What the interviewer is checking

Checks whether the candidate knows the pattern's real intent (aggregate-level persistence abstraction) and can explain why a generic repository over EF Core usually hurts.

Green flags

  • Says one repository per aggregate root, not per table.
  • Knows DbContext/DbSet already implement Repository and Unit of Work.
  • Names concrete problems: leaky IQueryable, Update() marking all columns, Save() per repository.
  • Keeps SaveChanges out of the repository.
  • Lets queries bypass the repository with projections.

Red flags

  • "Every entity needs a repository."
  • Repository methods that each call SaveChanges.
  • Can't tell a repository from a DAO.
  • Thinks the repository exists mainly to make unit tests possible with mocks.

📚 Learn in depth

1. Where the pattern comes from

Fowler (Patterns of Enterprise Application Architecture, 2002) defines a repository as mediating between the domain and data mapping layers "using a collection-like interface for accessing domain objects". Evans (Domain-Driven Design, 2003) narrows it: provide repositories only for aggregate roots that need direct access, so every change goes through the root that guards the invariants.

 Application service / handler
        |  orders.GetAsync(id)          unitOfWork.SaveChangesAsync()
        v                                         |
  IOrderRepository  <----- domain owns the interface (DIP)
        ^
        |  implements
  EfOrderRepository --> ShopDbContext.Orders (DbSet<Order>) --> SQL Server
                              |
                        change tracker (unit of work)

The interface lives with the domain or application layer; the EF Core implementation lives in infrastructure. That's the Dependency Inversion Principle applied to persistence.

2. Repository vs DAO vs table data gateway

  • Table Data Gateway (Fowler): one object per table with SQL for that table (OrdersGateway.Insert(...)).
  • DAO (J2EE): similar, often per table, CRUD-shaped.
  • Repository: per aggregate, collection-shaped, returns fully loaded domain objects. Loading an Order includes its lines because the aggregate is the consistency boundary.

3. What EF Core already gives you

Pattern EF Core implementation
Repository DbSet<T>: Add, Remove, FindAsync, LINQ
Unit of Work Change tracker + SaveChangesAsync (one transaction by default)
Identity Map The change tracker returns the same instance for the same key in one context
Data Mapper Model configuration maps classes to tables

So the question is never "do I need a repository to use EF Core?" but "does an extra abstraction protect something?"

4. The generic repository failure modes

  1. Leaky IQueryable. GetAll() returns a query the caller extends. Behaviour depends on the provider (translation, client evaluation, tracking), so the abstraction hides nothing.
  2. Update() semantics. DbSet.Update sets every property's state to Modified and attaches the graph; tracked entities don't need it at all, because the change tracker already detected changes.
  3. Per-repository Save(). Breaks the unit of work and creates partial writes.
  4. Repositories for children. IRepository<OrderLine> lets code insert lines into a submitted order.
  5. Lowest common denominator. Every query becomes GetAll().Where(...) in services, so query logic spreads anyway.

5. Designing a specific repository

  • Methods per use case: GetAsync(OrderId), GetOpenForCustomerAsync(CustomerId), Add(Order).
  • No Update: load, call domain methods, commit.
  • Remove(Order) only if the domain really deletes.
  • Load the whole aggregate (owned types or Include), since partial aggregates break invariants.
  • For many filter combinations, accept a Specification rather than adding methods.

6. Cost

A repository adds one interface and one class per aggregate, plus an interface dispatch per call (nanoseconds; irrelevant next to a database round trip). The real cost is maintenance and the temptation to route every read through it. Reads for screens and reports should project directly with Select and AsNoTracking.

Try it yourself

  1. Build a generic Repository<T> with Save(), use two in one use case, make the second save fail, and look at the partial data.
  2. Call DbSet.Update on a tracked entity after changing one property and compare the generated UPDATE (with LogTo) to just calling SaveChangesAsync.
  3. Replace it with IOrderRepository and a single SaveChangesAsync; confirm one transaction in SQL Profiler or Extended Events.
  4. Try to add a line to a submitted order through the aggregate and through a child repository; write a test that proves only the first is possible.
  5. Write a query endpoint that projects from DbContext directly and compare its SQL to GetAll().ToList() then mapping.

💻 Code

An aggregate-specific repository, a unit of work owned by the use case, and the generic repository it replaces.

namespace Shop.Orders;

public enum OrderStatus { Draft, Submitted, Cancelled }

public sealed class Order
{
    private readonly List<OrderLine> _lines = [];

    private Order() { }                                  // for EF Core materialisation

    public Order(Guid customerId)
    {
        Id = Guid.CreateVersion7();                      // sortable ids index well in SQL Server
        CustomerId = customerId;
        Status = OrderStatus.Draft;
    }

    public Guid Id { get; private set; }
    public Guid CustomerId { get; private set; }
    public OrderStatus Status { get; private set; }
    public IReadOnlyList<OrderLine> Lines => _lines;

    // Invariants live on the aggregate root, so lines can't be changed behind its back
    public void AddLine(string sku, int quantity, decimal unitPrice)
    {
        if (Status != OrderStatus.Draft) throw new InvalidOperationException("Only draft orders can change.");
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
        _lines.Add(new OrderLine(sku, quantity, unitPrice));
    }

    public void Submit()
    {
        if (_lines.Count == 0) throw new InvalidOperationException("An order needs at least one line.");
        Status = OrderStatus.Submitted;
    }
}

public sealed class OrderLine(string sku, int quantity, decimal unitPrice)
{
    public string Sku { get; private set; } = sku;
    public int Quantity { get; private set; } = quantity;
    public decimal UnitPrice { get; private set; } = unitPrice;
}

// Narrow, domain-named, no SaveChanges and no IQueryable
public interface IOrderRepository
{
    Task<Order?> GetAsync(Guid id, CancellationToken ct);
    void Add(Order order);
}

public interface IUnitOfWork
{
    Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
namespace Shop.Infrastructure;

using Microsoft.EntityFrameworkCore;
using Shop.Orders;

public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options), IUnitOfWork
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder) =>
        modelBuilder.Entity<Order>(b =>
        {
            b.OwnsMany(o => o.Lines, l => l.Property(x => x.UnitPrice).HasPrecision(18, 2));   // owned: loaded with the root
            b.Navigation(o => o.Lines).HasField("_lines");
        });
}

internal sealed class EfOrderRepository(ShopDbContext db) : IOrderRepository
{
    public Task<Order?> GetAsync(Guid id, CancellationToken ct) =>
        db.Orders.SingleOrDefaultAsync(o => o.Id == id, ct);   // owned lines come with the aggregate

    public void Add(Order order) => db.Orders.Add(order);
}

// The use case commits once, so every change in it is one transaction
public sealed class SubmitOrderHandler(IOrderRepository orders, IUnitOfWork unitOfWork)
{
    public async Task HandleAsync(Guid orderId, CancellationToken ct)
    {
        var order = await orders.GetAsync(orderId, ct) ?? throw new KeyNotFoundException($"Order {orderId} not found.");
        order.Submit();                                    // no Update() call: the change tracker saw the change
        await unitOfWork.SaveChangesAsync(ct);
    }
}
// Program.cs: everything scoped, so one DbContext is shared per request
builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
builder.Services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ShopDbContext>());
builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();
builder.Services.AddScoped<SubmitOrderHandler>();

// The anti-pattern this replaces:
// public interface IRepository<T> where T : class
// {
//     IQueryable<T> GetAll();                 // leaks EF Core to every caller
//     Task<T?> GetByIdAsync(object id, CancellationToken ct);
//     void Update(T entity);                  // DbSet.Update marks every column modified
//     Task SaveAsync(CancellationToken ct);   // each repository commits separately: no unit of work
// }

⚠ Common mistakes

  • Mistake: Creating a generic IRepository<T> for every entity over EF Core. Why it is wrong: It re-implements DbSet<T> with less power and invites repositories for child entities that bypass aggregate rules. Instead: Use DbContext directly, or write aggregate-specific repositories.
  • Mistake: Exposing IQueryable<T> from the repository. Why it is wrong: Callers depend on EF Core translation and tracking anyway, so the abstraction hides nothing and query logic spreads. Instead: Return materialised aggregates, or accept a specification.
  • Mistake: Putting SaveChanges inside each repository method. Why it is wrong: Two repositories in one use case commit in separate transactions, causing partial writes. Instead: Commit once per use case through the DbContext or an IUnitOfWork.
  • Mistake: Calling repository.Update(entity) after modifying a tracked entity. Why it is wrong: DbSet.Update marks every column modified and attaches the whole graph; the change tracker already saw the change. Instead: Load, call domain methods, SaveChangesAsync.
  • Mistake: One repository per table. Why it is wrong: That's a DAO; children change outside their aggregate root. Instead: One repository per aggregate root.
  • Mistake: Routing every read and report through the repository. Why it is wrong: Loading full aggregates to map into DTOs over-fetches and tracks entities you never change. Instead: Project straight from DbContext with Select and AsNoTracking.
  • Mistake: Registering the repository as a singleton. Why it is wrong: It captures a scoped DbContext (a captive dependency) shared across requests and threads. Instead: Register it scoped.

🏛 Senior insight: trade-offs

I start from "DbContext is already a repository and a unit of work" and add a repository only where it protects something: a rich aggregate with invariants, a domain layer that must not reference EF Core, or a persistence technology that may genuinely change. For CRUD screens and queries, a repository is a pass-through I'd rather not maintain.

Option When it fits Cost When not to
DbContext directly in handlers CRUD, queries, small services EF Core in the application layer Rich aggregates that must be loaded whole
Aggregate-specific repository DDD domain with invariants One interface + class per aggregate Pure CRUD
Generic IRepository<T> Rarely; maybe a non-EF store with uniform CRUD Leaky, breaks UoW, invites child repositories Over EF Core
Repository + specifications Many filter combinations on one aggregate Specification infrastructure Few, stable queries

I measure the value by what changes when requirements change: if adding a query means touching an interface, an implementation and a test double with no new behaviour, the layer isn't paying for itself.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions repositories growing a method per query combination Why: Checks how to avoid repository-method explosion with composable expression-based rules
    How to answer

    A specification wraps one business rule ("in stock", "price below X") in an object that exposes it as an Expression<Func<T,bool>>. Because it's an expression tree, EF Core translates it to SQL; compile it once and the same rule also works in memory (IsSatisfiedBy).

    Rules compose with And/Or/Not, built from Expression.AndAlso/OrElse/Not plus an ExpressionVisitor that replaces parameters so both sides share one lambda parameter.

    That replaces a repository with dozens of GetProductsByXAndY methods with one ListAsync(spec) and small, named, testable rules. Ardalis.Specification packages this with ordering, includes and paging.

    The trap: a spec typed as Func<T,bool> binds to Enumerable.Where, so EF loads the whole table and filters in memory. The trade-off is reusable rules against another abstraction to learn.

  2. When: Candidate says a repository should only have the methods its use cases need Why: Checks applying Interface Segregation to keep repository interfaces narrow
    How to answer

    ISP says clients should not be forced to depend on methods they do not use. A fat interface such as IOrderService with 25 members couples every consumer to all of them, makes test doubles painful and pushes implementers to throw NotImplementedException. Split interfaces by what clients need (role interfaces): IOrderReader for queries, IOrderWriter for commands, IClock instead of a giant IUtilities. The BCL does this well (IReadOnlyCollection<T> versus ICollection<T>, IAsyncDisposable). Do not go to the extreme of one interface per method; group members that the same client uses together.

  3. When: Candidate describes a generic IRepository<T> registered once for every entity Why: Checks open-generic DI registration and its limits for IRepository<>
    How to answer

    You register the open types, services.AddScoped(typeof(IRepository<>), typeof(Repository<>)), and when someone asks for IRepository<Order> the container closes the implementation with MakeGenericType and builds it, caching that plan. An exact closed registration for IRepository<Order> wins over the open one, while IEnumerable<IRepository<Order>> returns both. Lifetimes are per closed type. Microsoft DI has no decorator support, so I use Scrutor's Decorate for open generics or write it by hand. ValidateOnBuild cannot check open generics, so I add tests that resolve real closed types.

  4. When: Candidate says DbContext is already a repository and unit of work Why: Checks the architecture decision of whether to wrap EF Core at all
    How to 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.

  5. When: Candidate keeps SaveChanges out of repository methods Why: Checks why SaveChanges belongs to the unit of work, not the repository
    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.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me