gpt4 book ai didi

asp.net-core - Blazor 在上一个操作完成之前在此上下文中启动了第二个操作

转载 作者:行者123 更新时间:2023-12-04 12:17:07 25 4
gpt4 key购买 nike

我动态创建 NavMenu 并返回菜单我用户的数据库和索引页中我已经返回了数据库中的某些内容但是当我运行应用程序或重新加载它时会显示以下错误

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.



导航菜单代码,
List<Menu> menus = new List<Menu>();

protected override async Task OnInitializedAsync()
{
menus = await MenuService.GetMenus();

}

索引代码
@if (priorities == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
@foreach (var priority in priorities)
{
<tr>
<td>@priority.Name</td>
</tr>
}
</tbody>
</table>
}

@code {
List<Priority> priorities;

protected override async Task OnInitializedAsync()
{
priorities = await PriorityService.GetPriorities();

}
}

最佳答案

解决方案是使用 `DbContextFactory :
Quoting docs :

Some application types (e.g. ASP.NET Core Blazor) use dependency injection but do not create a service scope that aligns with the desired DbContext lifetime. Even where such an alignment does exist, the application may need to perform multiple units-of-work within this scope. For example, multiple units-of-work within a single HTTP request.

In these cases, AddDbContextFactory can be used to register a factory for creation of DbContext instances. For example:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextFactory<ApplicationDbContext>(
options =>
options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test"));
}

关于asp.net-core - Blazor 在上一个操作完成之前在此上下文中启动了第二个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58046008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com