【问题标题】:userManager.GetRolesAsync() returns list of roles but userManager.GetUsersInRoleAsync() returns empty listuserManager.GetRolesAsync() 返回角色列表,但 userManager.GetUsersInRoleAsync() 返回空列表
【发布时间】:2020-10-15 10:04:36
【问题描述】:

问题

以下代码获取用户的角色,但不获取该特定角色的用户。有什么遗漏吗?

代码

    public void SeedRolesData(PartnerDbContext context)
    {
        if (!context.Roles.Any())
        {
            context.Roles.AddRange(this.Roles);
            context.SaveChanges();
        }
    }

    public void SeedUserRoles(PartnerDbContext context)
    {
        if (!context.UserRoles.Any())
        {
            context.UserRoles.AddRange(this.UserRolesMapping);
            context.SaveChanges();
        }
    }

    public List<IdentityRole> Roles => new List<IdentityRole>
    {
        new IdentityRole { Id="1", Name = ApplicationDefaultRoles.admin }
    };

    public List<IdentityUserRole<string>> UserRolesMapping => new List<IdentityUserRole<string>>
    {
        new IdentityUserRole<string> { UserId = "1", RoleId = "1" }
    };

按用户获取角色和按角色获取用户

   var roles = userManager.GetRolesAsync(new User() {
    Id = "1",
    UserTypeId = (int)UserTypeEnum.admin,
    FirstName = "Sam",
    LastName = "Ram"
   }).Result; --> Returns result

   var user= userManager.GetUsersInRoleAsync(ApplicationDefaultRoles.admin).Result; --> Returns empty list.

【问题讨论】:

    标签: entity-framework asp.net-identity ef-core-2.2 usermanager


    【解决方案1】:

    角色的示例数据还应包括 NormalizedName 以获取角色中的用户。以下是更新后的示例角色数据。

        public List<IdentityRole> Roles => new List<IdentityRole>
        {
            new IdentityRole {
            Id="1", 
            Name = ApplicationDefaultRoles.admin, 
            NormalizedName = ApplicationDefaultRoles.admin.ToUpperInvariant() }
        };
    

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2021-03-11
      • 2015-10-27
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多