Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

asp.net core - Blazor A second operation started on this context before a previous operation completed

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

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.

NavMenu code,

List<Menu> menus = new List<Menu>();

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

}

Index code

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

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution is to use a `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"));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...