How do I get the List of Role and Number of users

2019-08-17 17:23发布

问题:

Please how do I get the list of roles, along with the number of users having the role? something like this

I have tried this

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

but this is just for one role. I need it for all the roles, and when a new role is added in the db, it should also add to the list.

Thanks

回答1:

Following code will be helpful to you.

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


回答2:

I know this question is over a year old, but here is an update in ASP Core 2.2.
This code runs on a PageModel, and things are getting simpler :)

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

Cheers