【问题标题】:(EFCore & Identity) A second operation started on this context before a previous operation completed(EFCore 和 Identity)在前一个操作完成之前在此上下文上启动了第二个操作
【发布时间】:2020-12-18 02:26:21
【问题描述】:

我从从 blazor 服务器端组件调用的方法中收到此错误:

System.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. 
    Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
       at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
       at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
       at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
       at BlazorStore9.Business.Account.GetProfileAndRoles(Int32 profileID) in 

从这个方法:

 public async Task<EditBlogUserModel> GetProfileAndRoles(int profileID)
    {
        Profile profile = await context.Profiles.AsNoTracking().FirstOrDefaultAsync(p => p.Id == profileID);
        if (profile == null)
            return null;
        //context.Entry(profile).State = EntityState.Detached;
        AppUser user = null;
        try
        {
            user = await userManager.FindByNameAsync(profile.UserName);
        }
        catch (Exception ex)
        { }
        var roles = await roleManager.Roles.ToListAsync<IdentityRole>();
        List<string> allRoles = roles.Where(r => r.Name != "Administrators" && r.Name != "Editors" && r.Name != "Users")
            .Select(r => r.Name).ToList<string>();
        IList<string> userRoles1 = await userManager.GetRolesAsync(user);
        List<string> userRoles = userRoles1.Where(r => r != "Administrators" && r != "Editors" && r != "Users").ToList<string>();
        List<RoleModel> rolesModel = new List<RoleModel>();
        var keyValuePairs = configuration.GetSection("BlogRoles").GetChildren();
        foreach (string role in allRoles)
        {
            if (userRoles.Find(r => r == role) != null)
            {
                rolesModel.Add(new RoleModel() { Text = keyValuePairs.FirstOrDefault(kvp => kvp.Key == role).Value, Value = role, Checked = true });
            }
            else
            {
                rolesModel.Add(new RoleModel() { Text = keyValuePairs.FirstOrDefault(kvp => kvp.Key == role).Value, Value = role, Checked = false });
            }
        }
        return new EditBlogUserModel()
        {
            ProfileID = profileID,
            Name = profile.UserName,
            Email = profile.Email,
            Roles = rolesModel
        };
    }

我尝试将 Tolist() 转换为 ToListAsync() 和整个方法异步,但我仍然收到此错误。

其名称为 EditBlogUser.razor 并嵌套在其他组件中的某些级别的调用方组件:

protected override async Task OnInitializedAsync()
{
    await base.OnInitializedAsync();


    Model = await account.GetProfileAndRoles(ProfileID);
   

    StateHasChanged();

}

启动文件:

services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(
            Configuration["Connections:AppConnection:ConnectionString"]), ServiceLifetime.Transient);

        services.AddDbContext<IdentityContext>(options =>
            options.UseSqlServer(
                Configuration["Connections:IdentityConnection:ConnectionString"]), ServiceLifetime.Transient);

如何让它工作?

【问题讨论】:

标签: c# entity-framework-core blazor-server-side


【解决方案1】:

在列出用户配置文件的 blazor 组件中,我将每个组件放在 Bootstrap Popup 中,但是我从组件的 OnInitializedAsync 生命周期方法中调用 GetProfileAndRoles 方法,这导致所有弹出组件在父组件加载时初始化,所以我移动了 Initialization调用 GetProfileAndRoles 方法来弹出的 Click 事件的代码,现在组件仅使用 click 事件进行初始化。它正在工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2020-01-22
    • 2018-11-07
    相关资源
    最近更新 更多