查询身份中的用户列表以及他们的角色,会产生上下文线程安全问题

时间:2018-07-02 06:37:03

标签: c# asp.net-core-mvc asp.net-identity asp.net-core-2.0 identity

我有如下代码:

[HttpGet]
        public IActionResult UserList()
        {
            List<UserListViewModel> model = new List<UserListViewModel>();
            model = _userManager.Users.Select(u => new UserListViewModel
            {
                Id = u.Id,
                Name = u.UserName,
                Email = u.Email,
                RoleName = _userManager.GetRolesAsync(u).Result.Single()
            }).ToList();
            return View(model);
        }

我正在尝试获取用户及其角色的列表。每个用户仅分配一个角色。在上面的代码中运行会给我一些线程安全错误,如下所示,我无法理解。建议一些方法。

System.AggregateException: 'One or more errors occurred. (A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.)'

1 个答案:

答案 0 :(得分:0)

这是这行代码:

RoleName = _userManager.GetRolesAsync(u).Result.Single()

您不能在Entity Framework中使用异步方法。

我建议在LINQ查询中进行联接,然后返回UsersListViewModel。像这样:

var model = (
    from u in _userManager.Users
    join r in _userManager.Roles on u.Id equals r.UserId
    select new UserListViewModel
        {
            Id = u.Id,
            Name = u.UserName,
            Email = u.Email,
            RoleName = r.RoleName
        } 
).ToList();