代码之家  ›  专栏  ›  技术社区  ›  Charles de M.

Identity Core 2 IdentityRole是否缺少用户定义?

  •  1
  • Charles de M.  · 技术社区  · 8 年前

    我是否遗漏了什么,或者用户的定义是否已从中删除 IdentityRole 在Identity Core 2中?

    我正在使用asp。net core 2和我需要计算每个角色的用户数。这在Core 1中运行良好,使用了以下标准代码

    public class ApplicationRoleController : Controller
    {
        private readonly RoleManager<ApplicationRole> roleManager;    
        public ApplicationRoleController(RoleManager<ApplicationRole> roleManager)
        {
            this.roleManager = roleManager;
        }
    
        [HttpGet]
        public IActionResult Index()
        {
            List<ApplicationRoleListViewModel> model = new List<ApplicationRoleListViewModel>();
            model = roleManager.Roles.Select(r => new
            {
                RoleName = r.Name,
                Id = r.Id,
                Description = r.Description,
                NumberOfUsers = r.Users.Count
            }).ToList()
            .Select(r => new ApplicationRoleListViewModel
            {
                RoleName = r.RoleName,
                Id = r.Id,
                Description = r.Description,
                NumberOfUsers = r.NumberOfUsers
            }).ToList();
    
            return View(model);
        }
    

    在我使用Core 2的应用程序中 NumberOfUsers = r.Users.Count ,其中r是从类派生的 ApplicationRole 错误为“ApplicationRole不包含用户定义” 应用程序角色 继承自 识别符 .

    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using System;
    
    public class ApplicationRole : IdentityRole
    {
        public string Description { get; set; }
        public DateTime CreatedDate { get; set; }
        public string IPAddress { get; set; }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Elias K.    8 年前

    你可以用这个

    var admins = _userManager.GetUsersInRoleAsync("Admin").Result;
    var number = admins.Count;
    

    AspNetUsers AspNetUserRoles AspNetRoles。不知道为什么。说实话很令人沮丧。据说你可以重新实现它们,但到目前为止我没有运气。我在这里试图找到一种方法,列出所有用户及其所有角色。 我认为上面的代码是你需要的。

    此外,在控制器中也同样导入了\u userManager

    private readonly UserManager<ApplicationUser> _userManager;
    
    
        public MyControllerController(DBContext context, UserManager<ApplicationUser> userManager)
        {
            this.context = context;
            _userManager = userManager; ;
        }