获取ASP.NET Identity中关联用户的角色列表

问题描述 投票:1回答:1

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

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>
}
c# asp.net-mvc asp.net-identity ninject
1个回答
0
投票

这是ASP.NET身份的错过设计之一,没有捷径获取角色列表及其关联用户的方法。但是您可以通过以下方式获得额外的努力:

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

© www.soinside.com 2019 - 2024. All rights reserved.