1

I'm trying to have a razor component in a foreach loop. this razor component has a async method call in it's OnInitializedAsync override method.

@foreach (var user in users)
{
    <span> @user.Email </span>
    <span> - </span>
    <span> @user.FullName </span>
    <button @onclick = "@(e => DeleteUser(user.Id))" > delete </button>
    <button @onclick = "@(e => showEdit(user.Id))" > edit </button>
    <UserRoles UserId = "@user.Id" />
    <br />
}

UserRoles.razor

protected override async Task OnInitializedAsync()
{
    userRoles = await _userService.GetRoles(UserId);
    StateHasChanged();
}

UserService.cs

public async Task<IList<string>> GetRoles(string userId)
{
    var user = await _UserManager.FindByIdAsync(userId);
    return await _UserManager.GetRolesAsync(user);
}

I'm getting following 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.
    Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
    Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+AsyncEnumerator.MoveNextAsync()
    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
    Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.GetRolesAsync(TUser user, CancellationToken cancellationToken)
    Microsoft.AspNetCore.Identity.UserManager<TUser>.GetRolesAsync(TUser user)
    Core.Services.UserService.GetRoles(string userId) in UserService.cs
    +
        return await _UserManager.GetRolesAsync(user);
    PersianFlac.Shared.UserRoles.OnInitializedAsync() in UserRoles.razor
    +
        userRoles = await _userService.GetRoles(UserId);
    Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
    Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)

If there's only one user(foreach loop once) no error occurs.

3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.