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.
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.
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?
| Check | Expected behavior |
|---|---|
| Repeat the failing operation in development or staging | Sequential queries finish on one context, and simultaneous requests use different instances. |
| Repeat normal traffic and a relevant negative case | Valid 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.
Comments
Post a Comment