本文介绍了Blazor在先前的操作完成之前,在此上下文中开始了第二项操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I makes the NavMenu dynamically and return menu i the database by users and in the index page already i returned something in the database but when i run the application or reload it show me bellow error

NavMenu代码

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();

    }
}

推荐答案

看起来您正在为两个数据库请求共享同一个dbcontext实例,同时执行了Index和NavMenu.

It looks you are sharing same instance of dbcontext for both db requests, Index and NavMenu are executed at a time.

如果您使用的是DI,请检查是否可以使用 transient 代替范围.这将为每个组件创建新的dbcontext.

If you are using DI, check if, for you, it is possible to work with transient instead scoped. This will create new dbcontext for each component.

已编辑 (由于评论)

Blazor是一项新技术,它作为blazorserver托管模型工作,它看起来更像是台式机应用程序而不是MVC,它们不只是实时客户端应用程序而已.我想我们站在需要重新思考许多概念的新挑战之前,请参阅Daniel Roth(ASP.NET首席程序经理)关于如何在Blazor上处理EF .

Blazor is a new technology, in my opinion, working as blazorserver hosted model, it looks more like a desktop app than like an MVC, they are no requests just a live client app. I guess we stand before new challenges that need to rethink a lot of concepts, see Daniel Roth's (Principal Program Manager, ASP.NET) issue about how to deal with EF on Blazor.

修改

可能仅使用transient是不够的,请在此处查看我的答案,以为每个请求创建新范围.

Maybe use transient is not enough, see my answer here about to create a new scope for each request.

这篇关于Blazor在先前的操作完成之前,在此上下文中开始了第二项操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 17:03