C# 获取EF Core 3.1中的角色列表

C# 获取EF Core 3.1中的角色列表,c#,entity-framework,C#,Entity Framework,我想在不使用UserManager/RoleManager的情况下获得EF core中所有身份角色的列表。我正在使用EF Core 3.1 当前在我的启动中: services.AddIdentity<ApplicationUser, ApplicationRole>() .AddRoles<ApplicationRole>() .AddRoleManager<RoleManager<Applic

我想在不使用UserManager/RoleManager的情况下获得EF core中所有身份角色的列表。我正在使用EF Core 3.1

当前在我的启动中:

services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddRoles<ApplicationRole>()
                .AddRoleManager<RoleManager<ApplicationRole>>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders(); //2FA
其中我得到了一个错误:

Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ApplicationUserId'.'
最终目标是向ApplicationUser上下文添加ApplicationRole的ICollection,因为EF Core似乎不支持它。我甚至无法从一个用户角色到另一个角色进行LINQ2Query连接


非常感谢您的帮助,因为我在这方面花了很多时间。

好吧,我终于找到了答案,以防有人怀疑。无法正确映射角色,因为ApplicationDBContext继承了IdentityDbContext模型的错误配置。为此,必须创建自己的继承IdentityUserRole的类,并实现适当的IdentityDBContext

public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
现在,为了映射新实体,我将以下内容添加到modelBuilder中:

        modelBuilder.Entity<ApplicationUserRole>(entity =>
        {
            entity.HasOne(e => e.Role)
            .WithMany(e => e.UserRoles)
            .HasForeignKey(e => e.RoleId);

            entity.HasOne(e => e.User)
            .WithMany(e => e.UserRoles)
            .HasForeignKey(e => e.UserId);
        });

总结如下:

  • 指定IdentityDBContext的正确实例
  • 创建ApplicationUserRole的连接表实体
  • 设置虚拟属性以映射ApplicationUser和ApplicationRole
  • 设置虚拟属性以映射RoleId和与TKey匹配的用户ID
  • 使用modelbuilder创建实体映射,但不要使用ApplicationUser/ApplicationRole实体
  • Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ApplicationUserId'.'
    
    public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
    
    public class ApplicationUserRole : IdentityUserRole<string>
    {
        public ApplicationUserRole() : base()
        {
    
        }
    
        public virtual ApplicationUser User { get; set; }
    
        public virtual ApplicationRole Role { get; set; }
    }
    
    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
    
            modelBuilder.Entity<ApplicationUserRole>(entity =>
            {
                entity.HasOne(e => e.Role)
                .WithMany(e => e.UserRoles)
                .HasForeignKey(e => e.RoleId);
    
                entity.HasOne(e => e.User)
                .WithMany(e => e.UserRoles)
                .HasForeignKey(e => e.UserId);
            });
    
    var list = _context.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();