Entity Framework Core Intermediate

Async queries and SaveChangesAsync

Database calls spend most of their time waiting. Async EF Core methods free the web server's thread during that wait, so the same server handles more requests. This lesson covers the async methods, cancellation tokens and the mistakes that cause deadlocks or errors.

What await does during a query
  1. StartRequest arrivesA thread starts running the action
  2. Step 2await ToListAsyncQuery sent; the thread returns to the pool
  3. Step 3SQL Server worksNo thread is blocked while waiting
  4. Step 4Result arrivesA pool thread continues the action
  5. EndResponse sentMore requests served with the same threads

Why async

While SQL Server works on a query, a synchronous call blocks a thread doing nothing. Under load the server runs out of threads and requests queue up. With await, the thread goes back to the pool and serves other requests until the result arrives.

Async does not make a single query faster; it lets the app handle more queries at once.

The async methods

Every method that runs SQL has an async version: ToListAsync, FirstOrDefaultAsync, SingleAsync, AnyAsync, CountAsync, SumAsync, FindAsync, SaveChangesAsync, ExecuteUpdateAsync and ExecuteDeleteAsync. Building the query with Where, OrderBy and Select stays the same.

C#
public async Task<IActionResult> Index(string? q, CancellationToken ct)
{
    var products = await db.Products
        .Where(p => q == null || p.Name.Contains(q))
        .OrderBy(p => p.Name)
        .Select(p => new ProductRow(p.Id, p.Name, p.Price))
        .ToListAsync(ct);

    return View(products);
}

// Streaming large results without loading all into memory
await foreach (var order in db.Orders.AsNoTracking().AsAsyncEnumerable().WithCancellation(ct))
{
    await writer.WriteLineAsync($"{order.Id},{order.Total}");
}

Common mistakes

  • Calling .Result or .Wait() on an async call blocks the thread and can deadlock; use await all the way up.
  • Running two queries at once on the same DbContext (for example with Task.WhenAll) throws an error. A DbContext is not thread-safe; await each call, or use separate contexts.
  • Forgetting the CancellationToken: pass it so queries stop when the user closes the page.
  • Calling ToList() (sync) inside an async action: mixing works but loses the benefit.

Interview question

Can you run two EF Core queries in parallel with Task.WhenAll on the same DbContext?

No. A DbContext is not thread-safe and supports only one operation at a time, so starting a second query before the first finishes throws an InvalidOperationException. Await the queries one after another, or create a separate DbContext for each parallel query, for example with IDbContextFactory.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.