为什么在 Ef 核心数据读取器中打开我的连接
Why there is open my connection in Ef core datareader
我是新手。对我放轻松。
这是我的操作代码
[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);
}
并且在检查我的用户是否处于此角色时抛出此异常
{"There is already an open DataReader associated with this Connection which must be closed first."}
由此变化:
foreach(var user in userManager.Users)
{
try
{
if (await userManager.IsInRoleAsync(user, role.Name))
{
model.Users.Add(user.UserName);
}
}
catch (Exception ex)
{
throw;
}
}
为此:
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;
}
}
将 userManager.Users 放在 foreach 循环上会创建一个连接以从数据库中检索用户,并且在完成之前不会关闭,然后当您调用 userManager.IsInRoleAsync 时已经有一个连接打开分贝。
我是新手。对我放轻松。
这是我的操作代码
[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);
}
并且在检查我的用户是否处于此角色时抛出此异常
{"There is already an open DataReader associated with this Connection which must be closed first."}
由此变化:
foreach(var user in userManager.Users)
{
try
{
if (await userManager.IsInRoleAsync(user, role.Name))
{
model.Users.Add(user.UserName);
}
}
catch (Exception ex)
{
throw;
}
}
为此:
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;
}
}
将 userManager.Users 放在 foreach 循环上会创建一个连接以从数据库中检索用户,并且在完成之前不会关闭,然后当您调用 userManager.IsInRoleAsync 时已经有一个连接打开分贝。