如何获取其中的角色列表和用户数量asp.net mvc

时间:2018-01-17 04:18:03

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

请问如何获取角色列表以及拥有该角色的用户数量?像这样enter image description here

我试过这个

var users = allusers.Where(x => x.Roles.Select(role => role.Name).Contains(" User"))。count;

但这仅适用于一个角色。我需要它用于所有角色,并且当在db中添加新角色时,它也应该添加到列表中。

由于

2 个答案:

答案 0 :(得分:0)

以下代码对您有所帮助。

var  result = ( from r in userManager.UserRoles 
                join u in userManager.Users on r.UserId equals u.Id
                group  new { r, u } by new { r.RoleId } into grp
                select new { name = grp.FirstOrDefault().r.Name, count=grp.Count()}).ToList();

答案 1 :(得分:0)

我知道这个问题已有一年多了,但这是ASP Core 2.2中的更新。
这段代码在PageModel上运行,事情变得越来越简单:)

//Creation of class
public class RolesModel : PageModel
{
    private readonly UserManager<IdentityUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly ILogger<RolesModel> _logger;

    public RolesModel(
        UserManager<IdentityUser> userManager,
        RoleManager<IdentityRole> roleManager,
        ILogger<RolesModel> logger)
    {
        _userManager = userManager;
        _roleManager = roleManager;
        _logger = logger;
    }

//(...)
//Now check in some class 

public async Task<IActionResult> OnGetAsync()
{
    var RolesList = _roleManager.Roles.OrderBy(x => x.Name).ToList();

    foreach (var role in RolesList)
    {
        var RolesUserlist = await _userManager.GetUsersInRoleAsync(role.Name);
        _logger.LogInformation($"Role {role.Name} has {RolesUserlist.Count} users");    
    }
}

欢呼