Search code examples
c#asp.net-coreasp.net-core-identity

Im getting InvalidOperationException when using UserManager.IsInRoleAsync()


Im trying to get all users in the role that I'm editing. But when I load the page it keeps giving me

InvalidOperationException: Cannot set MySqlCommand.CommandText when there is an open DataReader for this command; it must be closed first.

public async Task<IActionResult> EditRole(string id)
{
    var role = await roleManager.FindByIdAsync(id);
    if(role == null)
     {
        ViewBag.ErrorMessage = $"Role with id = {id} cannot be found";
        return View("NotFound");
    }
    var model = new EditRoleModel
    {
        Id = role.Id,
        RoleName = role.Name
    };
    foreach(var user in userManager.Users)
    {
        var userInRole = await userManager.IsInRoleAsync(user, role.Name);
        if (userInRole)
        {
            model.Users.Add(user.UserName);
        }
    }
    return View(model);
}

I'm getting the error here

var userInRole = await userManager.IsInRoleAsync(user, role.Name);

Solution

  • The Users property is an IQueryable<User>, and it looks like it is keeping an open streaming query over the data while you iterate it, which is causing the problem if you try and execute a second operation.

    As such, assuming the user directory isn't huge, you can probably work around this by simply:

    foreach(var user in userManager.Users.ToList())
    {...}
    

    which completes thew first query eagerly before iterating.


    However! You probably want to look at GetUsersInRoleAsync instead:

    foreach (var user in userManager.GetUsersInRoleAsync(role.Name))
    {
        model.Users.Add(user.UserName);
    }