Why there is open my connection in Ef core datareader

157 Views Asked by At

I am a novice. Take it easy on me.
this is code for my action

[HttpGet]
    public async  Task<IActionResult> EditRole(string id)
    {
        var role = await roleManager.FindByIdAsync(id);
        if(role == null)
        {
            ViewBag.ErrorMessage = $"Role with Id = {id} cant be found";
            return View("NotFound");
        }

        var model = new EditRoleViewModel()
        {
            Id = role.Id,
            RoleName = role.Name
        };

        foreach(var user in userManager.Users)
        {
            try
            {
                if (await userManager.IsInRoleAsync(user, role.Name))
                {
                    model.Users.Add(user.UserName);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
            
        }

        return View(model);
    }

and when check my user is in this role throw this exception

{"There is already an open DataReader associated with this Connection which must be closed first."}

enter image description here

1

There are 1 best solutions below

2
MestreDosMagros On BEST ANSWER

Change from this:

 foreach(var user in userManager.Users)
        {
            try
            {
                if (await userManager.IsInRoleAsync(user, role.Name))
                {
                    model.Users.Add(user.UserName);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
            
        }

To this:

var users = userManager.Users.ToList();

 foreach(var user in users)
        {
            try
            {
                if (await userManager.IsInRoleAsync(user, role.Name))
                {
                    model.Users.Add(user.UserName);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
            
        }

Putting the userManager.Users on the foreach loop creates a connection to retrieve the users from the database and it is not closed until finished, then when you call userManager.IsInRoleAsync there is already a connection open in the db.