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

📚 Interview question

What is the Unit of Work pattern? Explain how EF Core's DbContext already implements it with the change tracker and SaveChanges, when you need an explicit transaction (BeginTransactionAsync, execution strategies with retries), how ExecuteUpdate/ExecuteDelete fit in, and why all repositories in a request should share one DbContext.

Unit of Work in .NET: tracking changes and committing them as one transaction, EF Core's change tracker and SaveChangesAsync as the built-in UoW (implicit transaction, identity map), explicit transactions with BeginTransactionAsync for multiple SaveChanges or ExecuteUpdate/ExecuteDelete/raw SQL, wrapping them in CreateExecutionStrategy().ExecuteAsync when EnableRetryOnFailure is on, TransactionScope caveats, and sharing one scoped DbContext across repositories.

Intermediate Theory Intermediate design-patterns ef-core repository sql-server transactions unit-of-work

🎯 Key points

  • Unit of Work tracks every change made during a business operation and commits them together, or not at all (Fowler, PoEAA)
  • EF Core: the change tracker records Added/Modified/Deleted entities; one SaveChangesAsync sends them in one implicit transaction if none is open, but two separate SaveChangesAsync calls are two transactions
  • The change tracker is also an identity map: one instance per key per DbContext
  • Repositories must share the same scoped DbContext, otherwise each has its own unit of work and changes commit separately
  • Explicit transaction (Database.BeginTransactionAsync) is needed for several SaveChanges calls, ExecuteUpdate/ExecuteDelete or raw SQL that must commit together
  • With EnableRetryOnFailure, a user-initiated transaction must run inside CreateExecutionStrategy().ExecuteAsync, and the whole block may re-run, so it must be repeatable
  • ExecuteUpdateAsync/ExecuteDeleteAsync write straight to the database without updating tracked entities (they go stale) and commit immediately unless an explicit transaction is open
  • An IUnitOfWork interface is optional; DbContext can implement it to keep SaveChanges out of repositories; one context per request or message, never long-lived

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Unit of Work comes from Fowler's Patterns of Enterprise Application Architecture: an object keeps a list of everything a business operation changed, and at the end it writes all of it in one transaction. Either the order, its stock reservation and its audit row are all saved, or none are. You don't call the database on every property change, and you don't end up with half an operation saved.

EF Core's DbContext is exactly that. When I load an Order, the change tracker takes a snapshot; when I call order.Submit() and add a StockReservation, it knows one entity is Modified and one is Added. SaveChangesAsync works out the SQL, opens a transaction if none is active, sends the commands (batched), and commits. The change tracker is also an identity map, so loading the same order twice in one context gives me the same instance. The consequence for design is that every repository and handler in a request must use the same DbContext. EF's AddDbContext registers it as scoped, so repositories registered as scoped get that one instance. If a repository created its own context, or was a singleton holding one, I'd have two units of work and two commits.

The default isn't always enough. If I need two SaveChangesAsync calls, say to get a database-generated value before the next step, or I mix in ExecuteUpdateAsync, ExecuteDeleteAsync or ExecuteSqlAsync, I open an explicit transaction with Database.BeginTransactionAsync. Those Execute* methods run immediately and bypass the change tracker, so without that transaction they commit on their own. On Azure SQL I usually have EnableRetryOnFailure on, and then EF refuses a user-started transaction unless it runs inside CreateExecutionStrategy().ExecuteAsync. The whole block can re-run after a transient failure, so it has to be repeatable. The mistake I see is wrapping EF in a hand-written IUnitOfWork with its own transaction management that duplicates SaveChanges. DbContext already is the unit of work; my job is to keep it to one per operation and to know when the implicit transaction isn't enough."


Implicit vs explicit transactions

Situation What to use
All changes tracked, one commit SaveChangesAsync (implicit transaction)
Several SaveChangesAsync calls must be atomic BeginTransactionAsync + CommitAsync
ExecuteUpdateAsync/ExecuteDeleteAsync/ExecuteSqlAsync with tracked changes Explicit transaction
EnableRetryOnFailure + explicit transaction CreateExecutionStrategy().ExecuteAsync(...) around it
Two databases or a database plus a broker Not a UoW problem: use the outbox, not distributed transactions

Change tracker states

State Set by SQL on save
Added Add INSERT
Modified Property change detected (snapshot compare) UPDATE of changed columns only
Deleted Remove DELETE
Unchanged Loaded, nothing changed None
Detached Not tracked None

Production example

A stock-reservation endpoint used ExecuteUpdateAsync to decrement stock and then SaveChangesAsync for the order. Under load, about 1 in 2,000 orders failed on save after the stock had already been decremented, leaving phantom reservations. Wrapping both in one explicit transaction inside the execution strategy brought the mismatch to zero in the next month's stock reconciliation.

🔍 What the interviewer is checking

Checks whether the candidate understands that DbContext is the unit of work, why the context must be shared within an operation, and when the implicit transaction isn't enough.

Green flags

  • Says DbContext + SaveChanges is the unit of work with an implicit transaction.
  • Knows repositories must share one scoped context.
  • Knows ExecuteUpdate/ExecuteDelete bypass the change tracker and commit immediately.
  • Mentions execution strategies with EnableRetryOnFailure and repeatable blocks.
  • Uses the outbox rather than distributed transactions for a broker.

Red flags

  • Calls SaveChanges in every repository method.
  • Writes a custom UoW that wraps DbContext with its own transaction logic.
  • Thinks TransactionScope is the default answer.
  • Doesn't know what the change tracker does.

📚 Learn in depth

1. The pattern

  Business operation (one request / one message)
     |
     |  register new / dirty / removed objects
     v
  Unit of Work  --- commit() --->  BEGIN TRAN
  (list of changes)                INSERT ... UPDATE ... DELETE ...
                                   COMMIT  (or ROLLBACK on any failure)

Fowler lists the responsibilities: register new, dirty and removed objects, then commit them in the right order inside one transaction. A related pattern, Identity Map, ensures each row is loaded into one object per unit of work.

2. How EF Core implements it

  • Change tracking. On query, EF stores a snapshot of original values. DetectChanges (called automatically by SaveChanges) compares current values to the snapshot.
  • Ordering. EF orders commands by foreign-key dependencies (principal inserts before dependents, dependents deleted first).
  • Batching. SQL Server provider batches commands (up to 42 by default per round trip, configurable with MaxBatchSize).
  • Implicit transaction. If no transaction is active, SaveChanges creates one and commits it; any failure rolls back everything.
  • Identity map. FindAsync checks the tracker before querying; tracking queries return the existing instance for a key.

3. Lifetime: one context per operation

AddDbContext registers DbContext as scoped: one per HTTP request, or per IServiceScope you create in a background worker or message handler. Repositories registered as scoped receive the same instance. Pitfalls:

  • Singleton repository holding a context: a captive dependency, shared across threads (DbContext isn't thread-safe).
  • Long-lived context in a worker: the change tracker grows without bound and serves stale data. Create a scope per message or batch.
  • IDbContextFactory in Blazor Server or parallel work: each CreateDbContext() is a separate unit of work, on purpose.

4. Explicit transactions

await using var tx = await db.Database.BeginTransactionAsync(ct);
// several SaveChangesAsync / ExecuteUpdateAsync / ExecuteSqlAsync
await tx.CommitAsync(ct);   // disposing without commit rolls back

The default isolation is the database's (READ COMMITTED on SQL Server; Azure SQL has READ_COMMITTED_SNAPSHOT on by default). You can pass an IsolationLevel. Savepoints (CreateSavepointAsync) allow partial rollback; EF uses them automatically when SaveChanges runs inside your transaction.

5. Execution strategies

EnableRetryOnFailure retries transient SQL errors (deadlocks, failovers, throttling). Retrying a single SaveChanges is safe, but EF can't retry half of your hand-opened transaction, so it throws unless you run the whole unit inside strategy.ExecuteAsync(...). That delegate may run more than once, so:

  • create or reload entities inside it, or clear the change tracker at the start;
  • don't call external services (email, HTTP) inside it.

6. TransactionScope

TransactionScope gives an ambient transaction. In async code you must pass TransactionScopeAsyncFlowOption.Enabled, and spanning two connections can escalate to a distributed transaction. On .NET (Core) distributed transactions are supported only on Windows (since .NET 7) and aren't supported by Azure SQL Database. For a database plus a message broker, use the outbox pattern.

7. Should you add IUnitOfWork?

Only to keep SaveChanges out of repositories and the application layer free of DbContext. Let DbContext implement it (Task<int> SaveChangesAsync(CancellationToken) already matches). A hand-written UoW that manages its own transactions and repository instances duplicates EF and usually gets disposal or retries wrong.

Try it yourself

  1. Log SQL with LogTo and call SaveChangesAsync with three changes; find the BEGIN TRANSACTION/COMMIT and the batch.
  2. Register a repository that creates its own DbContext; make the second save fail and observe the partial write.
  3. Mix ExecuteUpdateAsync and SaveChangesAsync without a transaction, throw between them, and inspect the data; then fix with BeginTransactionAsync.
  4. Turn on EnableRetryOnFailure, open a transaction without the execution strategy, and read the exception.
  5. In a BackgroundService, process 10,000 messages with one context, and watch memory with dotnet-counters; then create a scope per message.

💻 Code

DbContext as the unit of work, and an explicit transaction inside the execution strategy for an operation that mixes ExecuteUpdateAsync with tracked changes.

namespace Shop.Infrastructure;

using Microsoft.EntityFrameworkCore;

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

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

    protected override void OnModelCreating(ModelBuilder modelBuilder) =>
        modelBuilder.Entity<StockItem>().HasKey(s => s.Sku);   // not named Id, so the key must be configured
}

public sealed class Order
{
    public Guid Id { get; init; } = Guid.CreateVersion7();
    public required string Sku { get; init; }
    public int Quantity { get; init; }
    public string Status { get; set; } = "Placed";
}

public sealed class StockItem
{
    public required string Sku { get; init; }
    public int Available { get; set; }
}

public sealed record AuditEntry(Guid Id, string Action, DateTimeOffset At);
namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;
using Shop.Infrastructure;

public sealed class PlaceOrderHandler(ShopDbContext db, TimeProvider clock)
{
    public async Task<Guid> HandleAsync(string sku, int quantity, CancellationToken ct)
    {
        var strategy = db.Database.CreateExecutionStrategy();     // required when EnableRetryOnFailure is on

        return await strategy.ExecuteAsync(async () =>
        {
            db.ChangeTracker.Clear();                              // the block may re-run after a transient failure
            await using var tx = await db.Database.BeginTransactionAsync(ct);

            // Runs immediately and bypasses the change tracker: only atomic because of tx
            var reserved = await db.Stock
                .Where(s => s.Sku == sku && s.Available >= quantity)
                .ExecuteUpdateAsync(s => s.SetProperty(x => x.Available, x => x.Available - quantity), ct);

            if (reserved == 0) throw new InvalidOperationException($"Not enough stock for {sku}.");

            var order = new Order { Sku = sku, Quantity = quantity };
            db.Orders.Add(order);
            db.Audit.Add(new AuditEntry(Guid.CreateVersion7(), $"Order {order.Id} placed", clock.GetUtcNow()));

            await db.SaveChangesAsync(ct);                         // tracked changes in the same transaction
            await tx.CommitAsync(ct);                              // dispose without commit = rollback
            return order.Id;
        });
    }
}
// Program.cs: scoped context, so every repository/handler in a request shares one unit of work
builder.Services.AddDbContext<ShopDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Shop"),
        sql => sql.EnableRetryOnFailure(maxRetryCount: 5)));
builder.Services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ShopDbContext>());
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<PlaceOrderHandler>();

⚠ Common mistakes

  • Mistake: Giving each repository its own DbContext. Why it is wrong: Each context is a separate unit of work, so changes commit separately and can be half-saved. Instead: Register the context and repositories as scoped so they share one instance per operation.
  • Mistake: Calling SaveChangesAsync after every change. Why it is wrong: Each call is its own transaction; a later failure leaves earlier changes committed. Instead: Make changes, then save once at the end of the use case.
  • Mistake: Mixing ExecuteUpdateAsync/ExecuteDeleteAsync with SaveChangesAsync and expecting one commit. Why it is wrong: Execute* methods commit immediately on their own and bypass the change tracker. Instead: Wrap both in an explicit transaction.
  • Mistake: Opening BeginTransactionAsync with EnableRetryOnFailure on, outside an execution strategy. Why it is wrong: EF throws because it can't retry part of a user transaction. Instead: Wrap the whole unit in CreateExecutionStrategy().ExecuteAsync and make it repeatable.
  • Mistake: Sending emails or calling HTTP APIs inside the retried transaction block. Why it is wrong: A retry repeats the side effect, and a rollback can't undo it. Instead: Commit first, then publish via an outbox.
  • Mistake: Keeping one DbContext alive for a whole background worker. Why it is wrong: The change tracker grows without bound, data goes stale, and the context isn't thread-safe. Instead: Create a scope (or use IDbContextFactory) per message or batch.
  • Mistake: Writing a custom UnitOfWork class that manages its own transactions and repositories. Why it is wrong: It duplicates EF Core and often mishandles disposal and retries. Instead: Let DbContext implement a thin IUnitOfWork if you need the abstraction.

🏛 Senior insight: trade-offs

Most Unit of Work bugs I see aren't about the pattern; they're about boundaries. Either the operation has two contexts (two units of work pretending to be one), or it mixes immediate operations like ExecuteUpdate with tracked changes and assumes they commit together. I keep one scoped context per operation, save once, and reach for explicit transactions only when the operation really spans several commands.

Option When it fits Cost When not to
Implicit SaveChangesAsync Most use cases None Mixed immediate SQL + tracked changes
BeginTransactionAsync (+ execution strategy) Several saves, Execute*, raw SQL Longer locks, repeatable block Single save
TransactionScope Legacy code with several connections Async-flow flag, escalation risk Azure SQL, cross-platform services
Outbox Database + message broker Relay process, at-least-once delivery Pure database operations

I measure with SQL logging (count BEGIN TRANs per request), Application Insights dependency telemetry, and reconciliation queries that look for orphaned rows after failures.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says repositories must be scoped to share the DbContext Why: Checks the captive-dependency bug when a singleton holds the scoped DbContext
    How to answer

    A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.

    ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.

    The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.

  2. When: Candidate mentions two requests updating the same order Why: Checks optimistic concurrency with rowversion when two units of work change the same aggregate
    How to answer

    The State pattern makes behaviour depend on the current state and makes transitions explicit, so "ship a cancelled order" is rejected rather than a status field being overwritten.

    Three implementations, from lightest:

    • A switch expression on (state, trigger): a compact, readable transition table; anything not listed is rejected.
    • State classes (IOrderState per state): worth it when each state has substantial behaviour of its own.
    • The Stateless library (5.20.1): Permit, PermitIf guards, OnEntry actions, CanFire, and graph export, with external state storage so EF Core persists a plain Status column.

    Invalid transitions return 409 Conflict. Because two requests can both pass the check in memory, add a rowversion concurrency token so the second SaveChanges fails. The trade-off: a library and classes buy guards and visualisation at the cost of indirection; a switch table is often enough.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me