【发布时间】:2020-01-22 13:17:29
【问题描述】:
我动态地制作 NavMenu 并由用户在数据库中返回菜单,并且在索引页面中我已经在数据库中返回了一些内容,但是当我运行应用程序或重新加载它时显示以下错误
InvalidOperationException:在此上下文中启动了第二个操作 在之前的操作完成之前。这通常是由 不同的线程使用相同的 DbContext 实例。更多 有关如何避免 DbContext 线程问题的信息,请参阅 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();
}
}
【问题讨论】:
-
问题不在您发布的代码中。
-
显示 GetMenus() 和 GetPriorities() 以及它们如何获取和使用 dbContext。
-
看起来您正在为两个数据库请求共享相同的 dbcontext 实例。如果您使用 DI,请检查您是否可以使用
transient而不是scoped: stackoverflow.com/a/41924039/842935 -
哇。谢谢 dani herrera,正在工作。
-
好的。我将其发布为解决方案。
标签: asp.net-core blazor blazor-server-side blazor-client-side