简体   繁体   中英

A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same thread

I have an ASP.NET Core 3.1 Web API project with Microsoft.EntityFrameworkCore version 2.2.6 and Azure SQL as the data source for the application.

I have the following code for setting up the DbContext using a dependency injection Container in the Startup.cs

public static IServiceCollection AddAppDBConfiguration(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment webHostEnvironment) => services.AddEntityFrameworkSqlServer().AddDbContext<AppDbContext>(appDbContext =>
{
        var appDataDBconn = configuration[VaultKeys.DataDBConnString];
        if (webHostEnvironment.IsEnvironment(Constants.Local))
        {
            appDataDBconn = configuration.GetSection(nameof(ApplicationOptions.Local)).Get<Local>().LocalDataDBConn;
        }

        appDbContext.UseSqlServer(appDataDBconn, sqlServerOptionsAction: sqlOptions =>
        {
            sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
        });
    });

The repository class used in this case is also marked as scoped lifetime in this case.

There is no usage of async and await in the method defined at repository layer level.

[HttpGet("{input1}", Name = "TestMethod")]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public dynamic TestMethod(string input1) => _testRepo.UpdateData(input1);

public class TestRepo : ITestRepo
{
    private static AppDbContext _appDbContext;
    public TestRepo(AppDbContext appDbcontext)
    {
        _appDbContext = appDbcontext;
    }

    public dynamic UpdateData(string input1) => _appDbContext.TestTable.Where(e => e.TestName == input1).Select(e => e.TestId).FirstOrDefault();
}

In the Azure AppInsights, I came across the below error

Error 500: System.InvalidOperationException for “GET TestController/TestMethod”.
   Error Message: 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, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations.

Can anyone help me to resolve this issue?

The context should not be static.

From DbContext Lifetime, Configuration, and Initialization :

public class MyController
{
    private readonly ApplicationDbContext _context;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM