我正在尝试为用户管理管理员页面提取所有我的Identity用户及其相关角色。我认为这将相当容易,但显然并非如此。我已经尝试按照以下解决方案进行操作:https : //stackoverflow.com/a/43562544/5392786,但到目前为止尚未解决。
这是我到目前为止的内容:
应用用户:
public class ApplicationUser : IdentityUser { public List<IdentityUserRole > Roles { get; set; } } 数据库上下文
public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions options) : base(options) { } } 启动身份码
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.Stores.MaxLengthForKeys = 128) .AddEntityFrameworkStores () .AddDefaultTokenProviders(); 我要在其中显示列表的剃须刀页面:
public class IndexModel : PageModel { private readonly UserManager userManager;
public IndexModel(UserManager<ApplicationUser> userManager)
{
this.userManager = userManager;
}
public IEnumerable<ApplicationUser> Users { get; set; }
public void OnGetAsync()
{
this.Users = userManager.Users.Include(u => u.Roles).ToList();
}
} 致电时出现以下错误userManager.Users.Include(u => u.Roles).ToList();:
MySql.Data.MySqlClient.MySqlException:'字段列表中的未知列'u.Roles.ApplicationUserId'''
我现在已经实现了以下解决方案。
正如CodeNotFound在注释中指出的那样,IdentityUser曾经具有一个Roles属性。.NET Core中不再是这种情况。GitHub上的此注释/问题似乎是.Net Core的当前解决方案。我试图用以下代码实现它:
应用用户
public class ApplicationUser : IdentityUser { public ICollection UserRoles { get; set; } } ApplicationUserRole
public class ApplicationUserRole : IdentityUserRole { public virtual ApplicationUser User { get; set; } public virtual ApplicationRole Role { get; set; } } 应用角色
public class ApplicationRole : IdentityRole { public ICollection UserRoles { get; set; } } 数据库上下文
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim , ApplicationUserRole, IdentityUserLogin , IdentityRoleClaim , IdentityUserToken > { public ApplicationDbContext(DbContextOptions options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUserRole>(userRole =>
{
userRole.HasKey(ur => new { ur.UserId, ur.RoleId });
userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});
}
} 启动
services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.Stores.MaxLengthForKeys = 128) .AddEntityFrameworkStores () .AddDefaultTokenProviders(); 最后,请确保在使用它时先加载用户的UserRoles,然后再加载UserRole的Role,如下所示:
this.Users = userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList(); 我有一个问题,其中Role每个属性UserRole均为null,并通过添加.ThenInclude(ur => ur.Role)零件来解决。
关于多级紧急加载的Microsoft文档:https : //docs.microsoft.com/zh-cn/ef/core/querying/related-data#includes-multiple-levels
ASP Core 2.2更新
IdentityUserRole 不是字符串的固有特性您可能还需要删除ModelBuilder中的代码才能使迁移正常进行。来源:stack overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。