Entity Framework Code First 为 TPT 继承覆盖 onModelCreating() 搞砸身份用户和角色模型

Entity Framework Code First override onModelCreating() for TPT Inheritance Screwing Up Identity User and Role Models

我在将 Fluent API 扩展到我的继承 类 时遇到问题。我采用了 TPT(table per type)方法,每种类型的继承都有一个 table。我喜欢 table 每种类型,因为数据库是完全规范化的并且易于维护。我在覆盖此 article 指示我执行的 onModelCreating 方法时遇到错误。它正在丢失用户和角色实体的密钥。

基础摘要Class

namespace Home_Warranty.Models
{
    public abstract class Vendor
    {
        [Key]
        public int VendorID { get; set; }

        [Required]
        public string CompanyName { get; set; }

        [Required]
        public int StreetNumber { get; set; }

        [Required]
        public string StreetName { get; set; }

        }
}

从供应商

继承了 ServiceCompany Class
namespace Home_Warranty.Models
 {
 [Table("ServiceCompanies")]
 public class ServiceCompany : Vendor
 {
    public string ACHClaim { get; set; }

    public virtual ICollection<SubContractorCompany> SubContractorCompanies{ get; set; }

    public virtual ICollection<ServiceCompanyUser> SubContractorUsers { get;set; }
    }
}

我在其中添加实体模型以启用 Fluent API 和 onModelCreating()

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public DbSet<Vendor> Vendors { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ServiceCompany>().ToTable("ServiceCompanies");

    }


    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

我在更新数据库时遇到以下迁移错误。这绝对是因为我重写了 onCreateModel 函数。

at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
One or more validation errors were detected during model generation:
Home_Warranty.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
Home_Warranty.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
  1. 这似乎不是解决问题的最佳方式。我可以在其他地方添加此代码并获得我想要的实际结果,而不会搞砸用户和角色模型吗?
  2. 我希望能够用流利的语言做这样的事情API。

var ListofServiceCompanies = db.ServiceCompanies.All()

还是我应该直接通过供应商实体?

var ListofServiceCompanies = db.Vendor.SelectMany( Vendor is a ServiceComapny...etc)

我更喜欢正确设置实体并使代码美观易用。任何见解或知识都将受到赞赏。

您的身份实体的所有配置都定义在 IdentityDbContext<ApplicationUser> 中。因此,如果您创建从 IdentityDbContext<ApplicationUser> 派生的自定义上下文 ApplicationDbContext,您需要在为自己的实体添加配置之前调用此行 base.OnModelCreating(modelBuilder);,如下所示:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<ServiceCompany>().ToTable("ServiceCompanies");
}