Missed User 属性,用于计算 asp.net 核心身份中的用户/角色数

Posted

技术标签:

【中文标题】Missed User 属性,用于计算 asp.net 核心身份中的用户/角色数【英文标题】:Missed User property, for counting number of user/roles in asp.net core identity 【发布时间】:2020-08-02 06:32:01 【问题描述】:

场景:

我有一个使用身份验证的 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>
            

提前致谢

【问题讨论】:

【参考方案1】:

这适用于所有角色。

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;

【讨论】:

感谢您的解决方案,但是有什么办法不使用 UserRoles 表和 lambda 表达式,而只使用这一行 NumberOfUsers = r.User .count? 对不起伙计,但我现在不知道这种方式

以上是关于Missed User 属性,用于计算 asp.net 核心身份中的用户/角色数的主要内容,如果未能解决你的问题,请参考以下文章

wordpress定时发布失败Missed Schedule解决方法

quartz问题记录-missed their scheduled fire-time

解决apscheduler报错:Run time of job …… next run at: ……)” was missed by

使用quartz出现这个错误 Handling 3 trigger(s) that missed their scheduled fire-time怎样解决呢?

6days before the day of your missed period(5 days before the day of your expected period 啥意思

相当于在 Swift Combine 中使用 @Published 计算的属性?