我正在像这样扩展IdentityUser
,IdentityUserRole
和IdentityRole
:
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public virtual ICollection<ApplicationIdentityUserRole> Roles { get; } = new List<ApplicationIdentityUserRole>();
}
public class ApplicationIdentityUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
}
public class ApplicationRole : IdentityRole
{
public virtual ICollection<ApplicationIdentityUserRole> Roles { get; } = new List<ApplicationIdentityUserRole>();
}
并配置如下:
public class SmartAccountingSetUpContext : IdentityDbContext<ApplicationUser>
{
public SmartAccountingSetUpContext(DbContextOptions<SmartAccountingSetUpContext> options)
: base(options)
{
}
public DbSet<ApplicationUser> Users { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Ignore<RegistrationViewModel>();
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<ApplicationUser>().ToTable("AspNetUsers");
builder.Entity<ApplicationIdentityUserRole>().ToTable("AspNetUserRoles");
builder.Entity<ApplicationRole>().ToTable("AspNetRoles");
builder.Entity<ApplicationIdentityUserRole>()
.HasOne(p => p.User)
.WithMany(b => b.Roles)
.HasForeignKey(p => p.UserId);
builder.Entity<ApplicationIdentityUserRole>()
.HasOne(x => x.Role)
.WithMany(x => x.Roles)
.HasForeignKey(p => p.RoleId);
}
}
我不断得到这个:
"Invalid column name 'Discriminator'.\r\nInvalid column name 'Discriminator'.\r\nInvalid column name 'Discriminator'.\r\nInvalid column name 'Discriminator'."
我知道如果您有派生类,则必须在OnModelCreating方法中指定HasDiscriminitor。但是IdentityUser,IdentityUserRole和IdentityRole不是抽象类。
我该如何克服?
最佳答案
您的上下文继承了 IdentityDbContext<TUser>
,而TPH (Table Per Hierarchy) Inheritance Strategy又继承了IdentityDbContext<TUser, IdentityRole, string>
。在这种情况下,TUser
是您的ApplicationUser
,但角色类型是IdentityRole
。
因此,基类的流利配置将IdentityRole
注册为实体。当您将派生的ApplicationRole
注册为实体时,EF Core会将其视为 Discriminator
,这是通过具有IdentityDbContext
列的单个表实现的。
要解决此问题,只需使用适当的基本通用IdentityUserRole
即可。由于您还具有自定义的IdentityDbContext<TUser,TRole,TKey,TUserClaim,TUserRole,TUserLogin,TRoleClaim,TUserToken>
派生类型,因此应将其与所有通用类型参数一起使用-ojit_a:
public class SmartAccountingSetUpContext : IdentityDbContext
<
ApplicationUser, // TUser
ApplicationRole, // TRole
string, // TKey
IdentityUserClaim<string>, // TUserClaim
ApplicationIdentityUserRole, // TUserRole,
IdentityUserLogin<stringy>, // TUserLogin
IdentityRoleClaim<string>, // TRoleClaim
IdentityUserToken<string> // TUserToken
>
{
// ...
}