【发布时间】:2021-04-11 05:00:21
【问题描述】:
我在文本之后有类似 DeleteSettingAbout() 的方法,但我仍然收到错误:"System.InvalidOperationException: 在前一个操作完成之前在此上下文上启动了第二个操作。这通常是由不同的线程引起的使用相同的 DbContext 实例。有关如何避免 DbContext 线程问题的更多信息,请参阅https://go.microsoft.com/fwlink/?linkid=2097913."。
方法代码为:
public async Task DeleteSettingAbout(int Id)
{
SettingAbout setting = await _context.SettingsAbout.FirstOrDefaultAsync(o => o.Id == Id);
if (setting != null)
{
_context.SettingsAbout.Remove(setting);
await _context.SaveChangesAsync();
}
}
在 sartup.cs 中,我将 DBContext 和 DBRepository 设置为 Transient:
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppDBConnection")),
ServiceLifetime.Transient);
services.AddTransient<IAppDbRepository, SQLAppDbRepository>();
但我仍然收到此错误。
如何解决这种行为?感谢您的回答。
2021-01-06 更新
我尝试了创建“DbContextFactory”的方法,它解决了我的问题。我从示例应用程序https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/blazor/common/samples/3.x/BlazorServerEFCoreSample(此处提及:https://docs.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-3.1#sample-app-3x)中获得灵感。
现在我的 startup.cs 中有这个:
// new way suitable for Blazor - register factory and configure the options (new instance for each method call)
services.AddDbContextFactory<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppDBConnection")));
services.AddScoped<IAppDbRepository, SQLAppDbRepository>();
【问题讨论】:
-
你为什么不升级到Net5.0!您需要实现 dbcontext 工厂。请参阅文档:docs.microsoft.com/en-us/aspnet/core/blazor/…
-
还有其他代码同时使用
_context吗? -
对于 enet:关于版本的好消息。但我的虚拟主机目前仅支持 .net core 3.1。我是 Blazor 的新手,所以感谢您推荐 dbcontext factory。
-
对于 Stephen Cleary:我会说不,因为我不知道同时使用 dbcontext 的其他代码。
-
对于 Nijenhof:明天我会尝试并给你回复。现在我在移动...
标签: exception concurrency entity-framework-core blazor ef-core-3.1