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().
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.
"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
IQueryablesends SQL. If I writevar q = db.Orders.Where(...)and then callq.Count(),q.Any()andforeach (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 lazyIEnumerable<Order>hasn't run anything. If the caller enumerates it after the scope that owns theDbContexthas ended, for example in a background continuation, or because a handler returned the query and the serialiser enumerated it later, EF Core throwsObjectDisposedException. The third class is overlapping commands. While Iforeachover a query, aDbDataReaderis open on the connection. If inside that loop I callSaveChangesAsyncor 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
foreachand 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 withToListAsync, 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 returnIReadOnlyList<T>from handlers. I stream withAsAsyncEnumerable()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."
| 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) |
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 |
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.
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
AsNoTracking for large exports and accepts the connection cost.Red flags
IQueryable from handlers to callers outside the unit of work.AsAsyncEnumerable is always better because it uses less memory.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.
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).
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.
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.
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.
Count, Any, foreach) with command logging on; count statements.IQueryable from a method that disposes its context, then enumerate it and read the exception.foreach over another query with and without MultipleActiveResultSets=True.gc-heap-size) for ToListAsync and AsAsyncEnumerable over 1 million rows.ChangeTracker.Entries().Count() grow; then add AsNoTracking().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);
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.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.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.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.AsNoTracking() plus streaming, or projection.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.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 |
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.
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.
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.
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.
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].
Last updated 23 Nov 2026.