C# 英孚核心;在上一个操作完成之前,在此上下文上启动了第二个操作";仅在部署时
我正在尝试创建一个web api,其中包含用于测试的非常基本的身份验证 我创建的上下文提供程序如下所示:C# 英孚核心;在上一个操作完成之前,在此上下文上启动了第二个操作";仅在部署时,c#,asp.net-web-api,entity-framework-core,C#,Asp.net Web Api,Entity Framework Core,我正在尝试创建一个web api,其中包含用于测试的非常基本的身份验证 我创建的上下文提供程序如下所示: services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient); 我已经尝试了所有我能想到的方法,上面提到的Appli
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
我已经尝试了所有我能想到的方法,上面提到的ApplicationDbContext是它唯一可以直接交互的方法,所以为什么它在部署时会出错,但在调试过程中使用相同的步骤却可以完全正常工作。你问题的奇怪之处在于,它在调试时可以工作。此异常表示您的
上下文
同时被两个线程使用,或者被同一请求中的两个线程使用,或者被两个请求使用
我认为它不会发生在您的计算机上的唯一原因是userManager.CreateAsync(用户,“Ali@123");代码>命令在调用下一行之前完成其执行。(大猜测)
当您使用CreateAsync
方法而不使用wait
时,可以在第一行完成执行之前执行下一行。此行为引发异常,并显示以下消息:“在上一个操作完成之前,在此上下文上启动了第二个操作”
要解决此问题,您需要等待至少第一个CreateAsync
调用
await userManager.CreateAsync(user, "Ali@123");
userManager.CreateAsync(user2, "Ali@123");
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");
}
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()
await userManager.CreateAsync(user, "Ali@123");
userManager.CreateAsync(user2, "Ali@123");