【问题标题】:Get role list with associated users in ASP.NET Identity获取 ASP.NET Identity 中关联用户的角色列表
【发布时间】:2019-02-16 16:19:43
【问题描述】:

我有一个角色。如何找到具有该角色的用户列表?

public ViewResult Index()
{
    return View(roleManager.RoleList.ToList());
}

在这种方法中,我使用用户UsersId 的角色列表。现在如何将它与我的UserModel 链接以获取UserName

我的 LINQ 不太好,找不到好主意

结果我想在视图中做一个表格

foreach (RoleModel role in Model)
{
            <tr>
                <td>@role.Id</td>
                <td>@role.Name</td>
                <td>@role.Description</td>
                <td>
                    @if (role.Users == null || role.Users.Count == 0)
                    {
                        @: Нет пользователей в этой роли
                    }
                    else
                    {
                        //User name which have that role
                    }
                </td>
            </tr>
}

【问题讨论】:

  • 如果你有 userManager 那么有一个方法userManager.GetUsersInRoleAsync
  • 我删除了我的答案,因为我忽略了您使用的是 ASP.NET MVC 而不是 Core。如果您有 UserManager,那么我会认为它会提供类似于 GetUserInRoleAsync 的方法。

标签: c# asp.net-mvc asp.net-identity ninject


【解决方案1】:

这是 ASP.NET Identity 的设计失误之一,没有捷径可以获取 Roles 列表及其关联的Users。但是您可以通过以下额外的努力获得:

public class RoleViewModel
{
   public string RoleId { get; set; }
   public string Name { get; set; }
   public string Description { get; set; }
   public List<UserViewModel> Users { get; set; }
}

public class UserViewModel
{
    public string UserId { get; set; }
    public string UserName { get; set; }
}

public ViewResult Index()
{
    List<RoleViewModel> rolesWithUsers = new List<RoleViewModel>();

    List<ApplicationRole> applicationRoles = RoleManager.Roles.Include(r => r.Users).ToList();

    foreach (ApplicationRole applicationRole in applicationRoles)
    {
        RoleViewModel roleViewModel = new RoleViewModel()
        {
                RoleId = applicationRole.Id,
                Name = applicationRole.Name,
                Description = applicationRole.Description
        };

        List<UserViewModel> usersByRole = UserManager.Users.Where(u => u.Roles.Any(r => r.RoleId == applicationRole.Id))
                .Select(u => new UserViewModel
                {
                    UserId = u.Id,
                    UserName = u.UserName
                }).ToList();
        roleViewModel.Users = usersByRole;

        rolesWithUsers.Add(roleViewModel);
    }

    return View(rolesWithUsers);
}

现在每个角色都有其关联的用户。

注意:从性能的角度来看,上述解决方案不是一个好的选择。这就是为什么最好将 ASP.NET 身份 实体与您自己的 DbContext 一起使用,而不是默认的 IdenityStote

【讨论】:

  • 如果我在视图中使用@using Domain.Entity @model IEnumerable&lt;RoleModel&gt;,则在 foreach 角色中具有只有 userId 和角色 Id 的属性用户
  • @remk93 请查看我的更新答案。在视图中请使用@using Domain.ViewModels @model IEnumerable&lt;RoleViewModel&gt;
  • 谢谢你,它工作正常,是的,你是对的,这不是最好的选择。但现在我才知道它是如何工作的,对我来说这不是一个糟糕的决定。
猜你喜欢
  • 1970-01-01
  • 2013-10-29
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
  • 2019-10-05
  • 1970-01-01
相关资源
最近更新 更多