'Error while fetching data using FindAsync in C#

Error message

Service registration

Method definition

Caller method

I am getting this error "A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913." when I call findAsync to fetch data based on a Id from db. I tried many solution but error persist. Here is my method definition.

    public async Task<T> GetById(Guid id)
    {
        var data =  await _dbContext.Set<T>().FindAsync(id);
        return data;
    }

I am calling it like this

    var dietPlan =  await _dietPlanRepositry.GetById(request.Id);

my db context service life time is Transient and repos are added as Transient

The screenshots of my code are attached



Solution 1:[1]

You should inject to you repository IServiceScopeFactory instead of DbContext.

And try to modify your GetById as follows:

public async Task<T> GetByIdAsync(Guid id)
{
   using (var scope = ScopeFactory.CreateScope())
   using (var db = scope.ServiceProvider.GetRequiredService<DbContext>())
   {
        var data =  await dbContext.Set<T>().FindAsync(id);
        return data;
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IKomarovLeonid