繁体   English   中英

EF Core“在上一个操作完成之前在此上下文中启动了第二个操作”仅在部署时

[英]EF Core "A second operation started on this context before a previous operation completed" only when deployed

我正在尝试创建一个具有非常基本的身份验证的 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 的上述使用是它直接与之交互的唯一时间,那么为什么它在部署时出错,但在调试中使用相同的步骤完全正常。

您问题的奇怪部分是它在您调试时有效。 此异常意味着您的context同时被两个线程使用,或者被同一请求中的两个线程使用,或者被两个请求使用。

我能想到它不会发生在你的机器上的唯一原因是userManager.CreateAsync(user, "Ali@123"); 命令在调用下一行之前完成其执行。 (大猜)

当您使用CreateAsync方法而不await它时,可以在第一行完成执行之前执行下一行。 这种行为会引发异常并显示以下消息: “在上一个操作完成之前,在此上下文上启动了第二个操作”

要解决此问题,您至少需要await第一次CreateAsync调用。

    await userManager.CreateAsync(user, "Ali@123");
    userManager.CreateAsync(user2, "Ali@123");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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