当我_userManager.FindByNameAsync(email)
时,我能够检索到正确的用户记录。但是,我的角色字段的计数为0.如果我查看数据库,实际上有与我的用户ID相关联的角色。
我在.NET 2.0上
在我的startup.cs中:
services.AddIdentity<ApplicationUser, ApplicationRole>
我的applicationRole:
public class ApplicationRole : IdentityRole
{
// public virtual ICollection<ApplicationUser> Users { get; } = new List<ApplicationUser>();
public ApplicationRole(){}
public ApplicationRole(string roleName) : base(roleName) {}
public virtual ICollection<IdentityUserRole<string>> Users { get; set; }
public virtual ICollection<IdentityRoleClaim<string>> Claims { get; set; }
}
我的应用程序用户:
public class ApplicationUser : IdentityUser
{
[InverseProperty("User")]
public virtual Player Player { get; set; }
public List<ApplicationUserClubs> Clubs { get; set; }
public int? CustomerProfileId { get; set; }
/// <summary>
/// Navigation property for the roles this user belongs to.
/// </summary>
public virtual ICollection<IdentityUserRole<string>> Roles { get; } = new List<IdentityUserRole<string>>();
}
我的查询是:
ApplicationUser user = await _userManager.FindByNameAsync(model.Email);
在我迁移到.NET 2.0之前,这曾经很好用。
编辑:
foreach (IdentityRole role in allRoles)
{
bool isUserInRole = role.Users.FirstOrDefault(x => x.Id == u.Id) != null;
userInRoles.Add(item: new AdminUserRoleViewModel
{
Id = role.Id,
Name = role.Name,
IsUserInRole = isUserInRole
});
}
我尝试做Role.Users时遇到异常。例外情况说:
'IdentityRole'不包含'Users'和no的定义 扩展方法'用户'接受类型的第一个参数 可以找到'IdentityRole'(你是否错过了使用指令或者 装配参考?
那时我决定使用自定义类ApplicationRole扩展IdentityRole
这里也是我的上下文文件:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<IdentityUser>().ToTable("AspNetUsers")
.HasKey(x => x.Id);
builder.Entity<IdentityRole>().ToTable("AspNetRoles")
.HasKey(x => x.Id);
builder.Entity<IdentityUserRole<string>>().ToTable("AspNetUserRoles")
.HasKey(x => new { x.UserId, x.RoleId });
builder.Entity<IdentityUserClaim<string>>().ToTable("AspNetUserClaims")
.HasKey(x => x.Id);
builder.Entity<IdentityUserLogin<string>>().ToTable("AspNetUserLogins")
.HasKey(x => new { x.UserId, x.ProviderKey });
builder.Entity<IdentityUserToken<string>>().ToTable("AspNetUserTokens")
.HasKey(x => new { x.UserId, x.LoginProvider, x.Name });
builder.Entity<IdentityRoleClaim<string>>().ToTable("AspNetRoleClaims")
.HasKey(x => x.Id);
builder.Entity<ApplicationUserToken>().ToTable("UserTokens")
.HasKey(x => x.Id);
}