2

设想:

我有一个使用身份验证的 Asp.net 核心程序。

目标:

我想获得具有如下特定角色的用户数量:

    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<ApplicationRole> _roleManager;

    public RoleController(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }

    public IActionResult Index()
    {
        List<roleListViewModel> model = new List<roleListViewModel>();
        model = _roleManager.Roles.Select(r => new roleListViewModel
        {
            id = r.Id,
            Name = r.Name,
            Description = r.Description,
            NumberOfUsers = r.User.count

        }).ToList();

        return View(model);
    }

问题是:

我在行中找不到用户NumberOfUsers = r.User.count

好榜样:

public class ApplicationRole:IdentityRole
{
    public string Description { get; set; }
}

角色视图模型:

public class roleListViewModel
{
    public string id { get; set; }

    [Required(ErrorMessage = "Name can not empty")]
    [Display(Name ="Name")]
    public string Name { get; set; }

    public int NumberOfUsers { get; set; }

    [Required(ErrorMessage = "Description can not empty")]
    [Display(Name = "Description")]
    public string Description { get; set; }
}

查看索引:

            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.Name</td>
                    <td>@item.Description</td>
                    <td>@item.NumberOfUsers</td>
                </tr>
            }

提前致谢

4

1 回答 1

3

这适用于所有角色。

var allUserRoles = _identityDb.UserRoles.ToList();
model = _roleManager.Roles.Select(r => new roleListViewModel
{
    Id = r.Id,
    Name = r.Name,
    Description = r.Description,
    NumberOfUsers = allUserRoles.Count(ur => ur.RoleId == r.Id)
}).ToList();

对于特殊角色

var usersBySpecialRole = _userManager.GetUsersInRoleAsync("myRole").Result;
于 2020-04-19T21:06:22.213 回答