Fix “A Second Operation Was Started” on an EF Core DbContext

Quick answer. Await each EF Core operation before starting another on the same context. If parallel work is required, create and dispose a distinct context for each operation.

Applies to. EF Core with the provider and version used by your application.

Entity Framework troubleshootingFind overlapping operationAwait or isolate contextsTest concurrent requests
Find overlapping operation → Await or isolate contexts → Test concurrent requests

What does the failure look like?

An API runs two queries with Task.WhenAll against one request-scoped context.

How do you diagnose the cause?

Look for missing awaits, Task.WhenAll, nested database operations during async enumeration, and shared contexts in background workers. A scoped lifetime controls how long a context lives. It does not serialize concurrent callers.

Worked example

Use sequential awaits when both queries belong to one unit of work. For independent parallel reads, use IDbContextFactory<T> and keep disposal inside each task. Create a fresh context for subsequent work after this InvalidOperationException.

C#
var orders = await db.Orders.ToListAsync(cancellationToken);
var users = await db.Users.ToListAsync(cancellationToken);

If the preview blocks the Copy button, select the snippet and copy it directly.

How do you verify the fix?

CheckExpected behavior
Repeat the failing operation in development or stagingSequential queries finish on one context, and simultaneous requests use different instances.
Repeat normal traffic and a relevant negative caseValid work completes and the failure path remains observable

These are expected outcomes. The example was not executed against a deployed application.

Frequently asked question

Is a scoped context thread-safe?

No. Use sequential operations per instance or an independent context per operation.

Microsoft Learn reference · ASP.NET tutorials

Comments