c# - 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 的上述使用是它直接与之交互的唯一时间,那么为什么它在部署时出错但在调试中使用相同的步骤却完全正常。
解决方案
推荐阅读
- api - 开发企业级和可扩展的现代 API Web 服务的方法
- java - 使用 rxJava 调用 API
- json - 如何在一个 json 提取器表达式中连接两个条件
- vba - 我可以使用 VBA 根据匹配条件过滤 Access 表单吗?
- botframework - 如何使用 BotFramework Composer 运行主动对话
- react-hook-form - react-hook-form FormContext 默认值问题
- android - 如何从当前导航路线中获取剩余路线/坐标
- jupyter - 如何在 Jupyter Lab 暗模式下使工具栏选择颜色可见?
- tensorflow - 获取特定层的输出作为测试数据的结果,而不是 keras 中的最后一层(自动编码器潜在特征)
- image - 从子文件夹中提取 .jpeg 文件并使用 SSIS 将它们放在另一个文件夹中