Get role list with associated users in ASP.NET Identity

随声附和 提交于 2021-01-28 05:22:40

问题


I have a role. How can I find the list of users which have that role?

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

In this method I take the list of roles there have the user's UsersId. Now how to link it with my UserModel to take the UserName?

I am not so good in the LINQ, and can't find a good idea

In the result I want to make a table in the view

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>
}

回答1:


This is one of the miss design of ASP.NET Identity that there is no short cut way of getting the list of Roles with its associated Users. But you can get with some extra effort as follow:

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);
}

Now each role will have its associated users.

Note : From performance standpoint, above solution is not a good option. That's why its always better to use ASP.NET identity entities with your own DbContext instead of default IdenityStote.



来源:https://stackoverflow.com/questions/54708568/get-role-list-with-associated-users-in-asp-net-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!