首页 > 解决方案 > EF Core“在前一个操作完成之前在此上下文上启动了第二个操作”仅在部署时

问题描述

我正在尝试创建一个具有非常基本身份验证的 Web api 以进行测试。

我像这样创建上下文提供程序:

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);

上下文类:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

}

我播种了一些用户:

public static void Initialize(IServiceProvider serviceProvider)
    {
        var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
        var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        context.Database.EnsureCreated();
            ApplicationUser user = new ApplicationUser()
            {
                Email = "a@gmail.com",
                SecurityStamp = Guid.NewGuid().ToString(),
                UserName = "a@gmail.com"
            };
            ApplicationUser user2 = new ApplicationUser()
            {
                Email = "ali@gmail.com",
                SecurityStamp = Guid.NewGuid().ToString(),
                UserName = "ali@gmail.com"
            };
        userManager.CreateAsync(user, "Ali@123");
        userManager.CreateAsync(user2, "Ali@123");
    }

然后我在我的控制器上使用 [Authorize] 属性。现在,当我调用这个 api时,它在调试时在 Visual Studio 中 100% 工作,根本没有 0 个问题。但是,当部署到同一台机器上的 IIS 时,出现错误:

System.InvalidOperationException: 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.

         at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()

         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

我已经尝试了几乎所有我能想到的东西,ApplicationDbContext 的上述使用是它直接与之交互的唯一时间,那么为什么它在部署时出错但在调试中使用相同的步骤却完全正常。

标签: c#asp.net-web-apientity-framework-core

解决方案



推荐阅读