How do I get the List of Role and Number of users in them asp.net mvc

倖福魔咒の 提交于 2020-01-16 08:51:04

问题


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



来源:https://stackoverflow.com/questions/48293526/how-do-i-get-the-list-of-role-and-number-of-users-in-them-asp-net-mvc

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