Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core: A second operation started on this context before a previous operation completed

I am not sure if you are using IoC and Dependency Injection to resolve your DbContext where ever it might be used. If you do and you are using native IoC from .NET Core (or any other IoC-Container) and you are getting this error, make sure to register your DbContext as Transient. Do

services.AddDbContext<MyContext>(ServiceLifetime.Transient);

OR

services.AddTransient<MyContext>();

instead of

services.AddDbContext<MyContext>();

AddDbContext adds the context as scoped, which might cause troubles when working with multiple threads.

Also async / await operations can cause this behaviour, when using async lambda expressions.

Adding it as transient also has its downsides. You will not be able to make changes to some entity over multiple classes that are using the context because each class will get its own instance of your DbContext.

The simple explanation for that is, that the DbContext implementation is not thread-safe. You can read more about this here


In some cases, this error occurs when calling an async method without the await keyword, which can simply be solved by adding await before the method call. however, the answer might not be related to the mentioned question but it can help solving a similar error.


The exception means that _context is being used by two threads at the same time; either two threads in the same request, or by two requests.

Is your _context declared static maybe? It should not be.

Or are you calling GetClients multiple times in the same request from somewhere else in your code?

You may already be doing this, but ideally, you'd be using dependency injection for your DbContext, which means you'll be using AddDbContext() in your Startup.cs, and your controller constructor will look something like this:

private readonly MyDbContext _context; //not static

public MyController(MyDbContext context) {
    _context = context;
}

If your code is not like this, show us and maybe we can help further.


I had the same problem and it turned out that parent service was a singelton. So the context automatically became singelton too. Even though was declared as Per Life Time Scoped in DI.

Injecting service with different lifetimes into another

  1. Never inject Scoped & Transient services into Singleton service. ( This effectively converts the transient or scoped service into the singleton. )

  2. Never inject Transient services into scoped service ( This converts the transient service into the scoped. )