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

📚 Interview question

What deferred-execution problems are specific to EF Core? Walk through a query enumerated twice, a query returned from a method and enumerated after the DbContext is disposed, and an unmaterialised query used inside a loop that also writes. When would you buffer with ToListAsync() and when would you stream with AsAsyncEnumerable()?

Covers EF Core-specific deferred-execution failures (repeated database round trips, ObjectDisposedException after scope end, open-reader conflicts and second-operation errors) and the buffering versus streaming choice between ToListAsync() and AsAsyncEnumerable().

Senior Theory Advanced async dbcontext deferred-execution ef-core iasyncenumerable streaming

🎯 Key points

  • An IQueryable is a recipe: every enumeration (foreach, Count, Any, ToList) is a new SQL round trip, and data changed in between gives inconsistent answers
  • An IQueryable or lazy iterator that was never materialised, enumerated after its DbContext is disposed -> ObjectDisposedException; the scope that owns the context must also execute the query
  • While a DbDataReader is open, the same connection can't run another command without MARS; MARS adds overhead and hides N+1
  • DbContext is not thread-safe in any mode: overlapping operations throw 'A second operation was started'
  • ToListAsync buffers: connection released quickly, memory = whole result
  • AsAsyncEnumerable / await foreach streams: constant memory, connection held for the whole loop
  • Streaming with tracking still grows the change tracker; use AsNoTracking for large streams
  • Materialise once at the boundary of the unit of work; return IReadOnlyList, not IQueryable, from handlers

⏱ 30-second answer

An EF Core IQueryable is a recipe, not data. Each enumeration (foreach, Count(), Any(), ToList()) sends SQL again, so enumerating twice is two round trips, and if rows change in between the two results disagree (a count of 10, then a loop over 11). A query returned from a method runs only when someone enumerates it; if the scope that owned the DbContext has ended and disposed it by then, you get ObjectDisposedException. And while a query is streaming, its DbDataReader holds the connection, so another command on the same context inside the loop fails (unless MARS is on) or is a hidden N+1. The context isn't thread-safe either, so overlapping operations throw.

ToListAsync() buffers: the connection is freed quickly, but memory holds the whole result. AsAsyncEnumerable() with await foreach streams in constant memory but holds the connection for the whole loop.

I materialise once, inside the unit of work, and stream only large, read-only, no-tracking results.

🗣 Full answer (senior)

How I would answer this in an interview

"In LINQ to Objects, deferred execution mostly costs CPU. In EF Core it costs round trips, connections and lifetime bugs, because every enumeration of an IQueryable sends SQL. If I write var q = db.Orders.Where(...) and then call q.Count(), q.Any() and foreach (var o in q), that's three separate queries, and if data changes in between they can disagree: the count says 10 and the loop sees 11.

The second class is lifetime. A repository method that returns IQueryable<Order> or a lazy IEnumerable<Order> hasn't run anything. If the caller enumerates it after the scope that owns the DbContext has ended, for example in a background continuation, or because a handler returned the query and the serialiser enumerated it later, EF Core throws ObjectDisposedException. The third class is overlapping commands. While I foreach over a query, a DbDataReader is open on the connection. If inside that loop I call SaveChangesAsync or run another query on the same context, SQL Server without MARS fails with 'There is already an open DataReader associated with this connection', or EF Core throws 'A second operation was started on this context instance' if the operations overlap.

For example, at [company] an [invoice export job] streamed invoices with foreach and called a lookup query per row, and it failed only in production because [the connection string differed]. I changed it to read invoices in pages with ToListAsync, prefetch the lookups in one query, and write in batches. So my rule is: materialise once, at the edge of the unit of work, and return IReadOnlyList<T> from handlers. I stream with AsAsyncEnumerable() only for big, read-only, no-tracking results like exports, and then I accept that the connection is held for the whole loop, so the loop body must be fast and must not use the same context."


The failure modes

Pattern What happens Fix
Same IQueryable enumerated twice Two SQL round trips; results may differ Materialise once into a list
Count() then foreach Two queries, race between them Single query, or count the list
Return IQueryable from a scoped service, enumerate later ObjectDisposedException Materialise inside the scope
Query inside a foreach over another query (same context) Open-reader error or N+1 Buffer the outer query, or prefetch with one query
SaveChanges inside a streaming loop Open-reader error (without MARS) Buffer, or batch writes after the loop
Task.WhenAll of queries on one context 'Second operation' error Sequential awaits or one context per task (IDbContextFactory)

Buffer or stream?

ToListAsync() AsAsyncEnumerable() + await foreach
Memory Whole result One row at a time (plus tracker if tracking)
Connection held Only while reading For the whole loop
Can use the context inside the loop Yes No (open reader)
Good for Request/response, small/medium results Exports, ETL, IAsyncEnumerable endpoints
Failure risk Out-of-memory on huge results Long-held connections, pool exhaustion, blocking

Production example

A nightly export of [~2 million] rows used ToListAsync() and peaked at [~3 GB], getting OOM-killed in a [2 GB] container. Switching to AsNoTracking().AsAsyncEnumerable() writing straight to a blob stream held memory at [~150 MB]; the loop body did no database work, so the single held connection was fine.

🔍 What the interviewer is checking

Checks that the candidate understands deferred execution in terms of round trips, context lifetime and connection usage, and can choose buffering versus streaming deliberately.

Green flags

  • Explains repeated enumeration as repeated SQL.
  • Knows the disposed-context and open-reader failures and why they occur.
  • Distinguishes MARS from the DbContext concurrency rule.
  • Chooses streaming with AsNoTracking for large exports and accepts the connection cost.

Red flags

  • Returns IQueryable from handlers to callers outside the unit of work.
  • Fixes open-reader errors by enabling MARS without addressing the loop.
  • Thinks AsAsyncEnumerable is always better because it uses less memory.

📚 Learn in depth

1. What enumeration does in EF Core

foreach / ToListAsync / Count / Any / First
   │
   ▼
QueryCompiler: cache lookup -> compiled query delegate
   ▼
RelationalCommand.ExecuteReaderAsync
   ▼
connection.Open (from pool) -> DbDataReader
   ▼
shaper materialises row by row  -> (tracking: identity map + snapshot)
   ▼
end of enumeration -> reader closed -> connection returned to pool (if EF opened it)

Each enumeration repeats the whole path. Aggregates (Count, Any) are different SQL statements, not reuses of an earlier result.

2. Lifetime: who owns the context

HTTP request scope
  └ DbContext (scoped)
      └ handler returns IQueryable<Order>   (nothing executed)
  scope ends -> DbContext.Dispose()
 serializer / caller enumerates -> ObjectDisposedException

The same happens with yield return iterators over a query in a method whose using var db = ... disposes the context when the iterator is created but not yet enumerated (or the reverse: a context that never gets disposed because the iterator is never completed).

3. One active command per connection

SQL Server's TDS protocol allows one active result set per connection unless MARS (MultipleActiveResultSets=True) is on. While a reader is open:

outer: foreach (var o in db.Orders)          <- reader open
 inner: db.Customers.Find(o.CustomerId)      <- needs the connection
        -> InvalidOperationException: There is already an open DataReader...

MARS makes it work but interleaves commands on one connection, has overhead, and still hides an N+1. Separately, DbContext has a concurrency detector: two overlapping operations (Task.WhenAll) throw 'A second operation was started on this context instance before a previous operation completed', regardless of MARS.

4. Buffering versus streaming

ToListAsync:          read all rows -> close reader -> return List<T>
                      memory O(n), connection O(read time)

AsAsyncEnumerable:    yield row -> your loop body runs -> next row ...
                      memory O(1)*, connection O(read time + loop time)
                      *tracking queries still keep every entity in the change tracker

ASP.NET Core can return IAsyncEnumerable<T> from an action and System.Text.Json streams it to the response. That holds a connection for the length of the response write, which on slow clients can be long; consider it for internal clients, and test pool usage under load.

Note: with split queries or some providers, EF Core may buffer internally even when you stream.

5. Making it explicit

A good boundary is: handlers return IReadOnlyList<T> (or a paged result), data access composes IQueryable internally, and anything that streams is named that way (StreamInvoicesAsync) and returns IAsyncEnumerable<T> with [EnumeratorCancellation] support.

Try it yourself

  1. Enumerate the same query three ways (Count, Any, foreach) with command logging on; count statements.
  2. Return an IQueryable from a method that disposes its context, then enumerate it and read the exception.
  3. Run a query inside a foreach over another query with and without MultipleActiveResultSets=True.
  4. Compare peak memory (dotnet-counters gc-heap-size) for ToListAsync and AsAsyncEnumerable over 1 million rows.
  5. Stream with tracking on and watch ChangeTracker.Entries().Count() grow; then add AsNoTracking().

💻 Code

Buffer inside the unit of work; stream only large read-only results; never reuse the context inside a streaming loop.

namespace Billing;

using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore;

public sealed record InvoiceRow(int Id, string Number, decimal Total, DateOnly IssuedOn);

public sealed class InvoiceQueries(BillingDbContext db)
{
    // BAD: deferred query escapes the scope; enumerated later -> ObjectDisposedException.
    public IQueryable<Invoice> Overdue() => db.Invoices.Where(i => i.DueOn < DateOnly.FromDateTime(DateTime.UtcNow));

    // GOOD: materialised once, inside the scope, as a read-only list.
    public async Task<IReadOnlyList<InvoiceRow>> OverdueAsync(DateOnly today, CancellationToken ct) =>
        await db.Invoices
            .Where(i => i.DueOn < today)
            .Select(i => new InvoiceRow(i.Id, i.Number, i.Total, i.IssuedOn))
            .ToListAsync(ct);

    // GOOD for exports: streams in constant memory. No tracking, and the caller must not
    // use this DbContext inside its loop because the reader holds the connection.
    public async IAsyncEnumerable<InvoiceRow> StreamForExportAsync(
        DateOnly from, [EnumeratorCancellation] CancellationToken ct = default)
    {
        var query = db.Invoices.AsNoTracking()
            .Where(i => i.IssuedOn >= from)
            .OrderBy(i => i.Id)
            .Select(i => new InvoiceRow(i.Id, i.Number, i.Total, i.IssuedOn))
            .AsAsyncEnumerable();

        await foreach (var row in query.WithCancellation(ct))
            yield return row;
    }
}
// BAD: second command while the outer reader is open (fails without MARS, N+1 with it).
foreach (var invoice in db.Invoices.Where(i => i.Status == InvoiceStatus.Draft))
{
    var customer = await db.Customers.FindAsync([invoice.CustomerId], ct);
    invoice.Finalise(customer!);
    await db.SaveChangesAsync(ct);
}

// GOOD: buffer the batch, prefetch lookups in one query, save once.
var drafts = await db.Invoices.Where(i => i.Status == InvoiceStatus.Draft).Take(500).ToListAsync(ct);
var customerIds = drafts.Select(d => d.CustomerId).Distinct().ToList();
var customers = await db.Customers.Where(c => customerIds.Contains(c.Id)).ToDictionaryAsync(c => c.Id, ct);
foreach (var d in drafts) d.Finalise(customers[d.CustomerId]);
await db.SaveChangesAsync(ct);

⚠ Common mistakes

  • Mistake: Enumerating the same IQueryable several times (Any(), Count(), then foreach). Why it is wrong: each is a SQL round trip and the results can disagree. Instead: materialise once and work on the list.
  • Mistake: Returning IQueryable or a lazy IEnumerable from a scoped service or handler. Why it is wrong: it executes after the context is disposed, or on a context other code is using. Instead: return IReadOnlyList<T> materialised inside the scope that owns the context.
  • Mistake: Running queries or SaveChanges inside a foreach over another query on the same context. Why it is wrong: the open reader blocks the connection (error without MARS) and it's an N+1. Instead: buffer the outer query and prefetch related data.
  • Mistake: Turning on MARS to make the open-reader error go away. Why it is wrong: MARS multiplexes several result sets over one connection, which adds per-command overhead and session state, has been linked to slower queries and odd blocking on SQL Server, and still leaves the N+1 in place. It also doesn't help with the DbContext concurrency rule. Instead: restructure the loop; keep MARS off unless legacy code truly needs it.
  • Mistake: Running queries on one context with Task.WhenAll. Why it is wrong: DbContext is not thread-safe and throws 'A second operation was started'. Instead: await sequentially, or create a context per task with IDbContextFactory.
  • Mistake: Streaming a huge result with tracking on. Why it is wrong: the change tracker still keeps every entity, so memory grows anyway. Instead: AsNoTracking() plus streaming, or projection.
  • Mistake: Doing slow work (HTTP calls) inside an await foreach over a query. Why it is wrong: the connection is held for the whole loop, risking pool exhaustion and long-held locks under some isolation levels. Instead: buffer a page, close the reader, then do the slow work.

🏛 Senior insight: trade-offs

Deferred execution is a feature inside the data layer and a liability outside it. I draw the boundary explicitly: composition with IQueryable stays in data access, handlers return materialised results, and streaming is opt-in and named. The real resource in EF Core isn't CPU; it's the pooled connection and the context's single-operation rule.

I measure buffering versus streaming with dotnet-counters (GC heap size, connection pool counters in Microsoft.Data.SqlClient.EventSource) under realistic load, not on a laptop.

Option When it fits Cost When not to
ToListAsync Request/response, results that fit in memory O(n) memory Millions of rows
AsAsyncEnumerable (no tracking) Exports, ETL, streaming endpoints Connection held for the loop Loop bodies that touch the same context or call slow services
Paged buffering (keyset batches) Large jobs that also write More code Small results
MARS Legacy code you can't restructure yet Overhead, hides N+1 New code

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions deferred execution in general LINQ terms. Why: Checks the general LINQ debugging story behind the EF Core specifics.
    How to answer

    Deferred execution means a LINQ query is a recipe that runs each time you enumerate it, not when you write it. That explains all four symptoms. The "changing" list is a query that re-reads its source and captured variables. The ObjectDisposedException comes from enumerating an EF query after the DbContext was disposed. Three log lines are three enumerations, and the late exception is a lambda failing during enumeration. I fix them by materialising once with ToList at a clear boundary inside the context's scope, and by turning on CA1851 for multiple enumeration.

  2. When: Candidate mentions 'A second operation was started on this context instance'. Why: Checks how they run database work in parallel correctly.
    How to answer

    A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.

  3. When: Candidate talks about returning IQueryable versus IEnumerable from repositories. Why: Checks the static-type and boundary decision.
    How to answer

    With EF Core, IQueryable<T> means "a query not yet sent": each LINQ operator adds to an expression tree, and the provider translates the whole tree into one SQL statement when you enumerate it. IEnumerable<T> means "objects in memory": operators are compiled delegates that run in your process over rows already fetched.

    • The compile-time type decides which Where you get: Queryable.Where(Expression<...>) or Enumerable.Where(Func<...>).
    • AsEnumerable() is only a cast and ToList() runs the query straight away, but after either one (or a method that returns IEnumerable<T>) every later filter, sort and Take runs in C#. The SQL that is sent no longer contains them, so the database can't use an index or TOP, and far more rows cross the wire.

    The trade-off: keep it IQueryable while the database can do the work, and switch to memory only for the last step SQL can't do.

🛠 Real-world problems: how you handle them

Invoice job failed only in production with an open DataReader error
Situation
A nightly [invoice finalisation] worker service processed [~80,000] draft invoices on Azure SQL. It passed in development and test.
Signals
Production runs failed after the first invoice with `InvalidOperationException: There is already an open DataReader associated with this Connection which must be closed first`; the job's duration alert fired; no invoices finalised that night.
Investigation
Compared configuration: development connection strings had `MultipleActiveResultSets=True`, production didn't. Reproduced locally without MARS. The code looped with `foreach` over a draft-invoice query and called `FindAsync` and `SaveChangesAsync` inside the loop. Command logging also showed [~160,000] queries in development: an N+1 that MARS had hidden.
Resolution
Immediate: re-ran the job with the loop changed to buffer each batch of 500 with `ToListAsync`. Real fix: keyset-paged batches, prefetching customers with one `Contains` query per batch, one `SaveChangesAsync` per batch, and `ChangeTracker.Clear()` between batches.
Prevention
Same connection-string options across environments (enforced in configuration review); integration test runs the job against SQL Server in a container without MARS; command-count metric emitted per batch; code-review rule against database calls inside loops over queries.

How to tell it (STAR)

**S:** At [company], our nightly invoice job failed in production after the first invoice, while every test environment passed. **T:** I had to get [that night's invoices] out and stop it recurring. **A:** I found that development used MARS and production didn't, and that the job streamed drafts with foreach while querying and saving inside the loop. That was an open-reader conflict in production and a hidden N+1 everywhere else. I rewrote it to buffer batches of 500, prefetch customers in one query, save once per batch and clear the tracker. **R:** The job went from [failing] to finishing in [~6 minutes instead of ~40 in test], with queries dropping from [~160,000 to ~330].

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me