InvalidOperationException:在上一个操作完成之前,在此上下文实例上启动了第二个操作。这通常是由不同线程同时使用同一个 DbContext 实例引起的。有关如何避免 DbContext 线程问题的更多信息,请参阅 https://go.microsoft.com/fwlink/?linkid=2097913。
我正在使用 ASP.NET Core 7。
我有一个用户控制器来管理身份用户,如下所示:
namespace Aqbel.Controllers;
public class UsersController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public UsersController(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<IActionResult> Index()
{
var users = await _userManager.Users.Select(user => new UserViewModel
{
Id = user.Id,
FirstName = user.FirstName,
LastName = user.LastName,
UserName = user.UserName,
Email = user.Email,
Roles = _userManager.GetRolesAsync(user).Result
}).ToListAsync();
return View(users);
}
}
索引查看如下
@model IEnumerable<UserViewModel>
@{ ViewData["Title"] = "Users"; }
<h1>@ViewData["Title"]</h1>
<a asp-action="Add" class="btn btn-primary">Add User</a>
<table class="table table-striped mt-4">
<thead>
<tr>
<th>Name</th>
<th>LastName</th>
<th>Username</th>
<th> Email</th>
<th>Roles</th>
<th>Manage Roles</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>@user.FirstName</td>
<td>@user.LastName</td>
<td>@user.UserName</td>
<td>@user.Email</td>
<td>@string.Join(" , ", user.Roles.ToList())</td>
<td>
<a class="btn btn-primary" asp-action="ManageRoles" asp-route- userId="@user.Id">Roles</a>
<a class="btn btn-outline-secondary" asp-action="Edit" asp-route-userId="@user.Id">Edit</a>
</td>
</tr>
}
</tbody>
</table>
代码中是否有任何错误导致出现此类错误?
您在
.Result
上使用 Task
,这是一个阻塞调用。
Roles = _userManager.GetRolesAsync(user).Result <--- problem here
我们可以像下面这样改变 Index 方法来解决这个问题。
public async Task<IActionResult> Index()
{
var users = await _userManager.Users.ToListAsync();
var userViewModels = new List<UserViewModel>();
foreach (var user in users)
{
var roles = await _userManager.GetRolesAsync(user);
userViewModels.Add(new UserViewModel
{
Id = user.Id,
FirstName = user.FirstName,
LastName = user.LastName,
UserName = user.UserName,
Email = user.Email,
Roles = roles
});
}
return View(userViewModels);
}