将 TPT 继承代码优先模型添加到 Linq Fluent API

Add TPT Inherited Code First Model to Linq Fluent API

我在将 Fluent API 扩展到我的继承 类 时遇到问题。我采用了 TPT(table per type)方法,每种类型的继承都有一个 table。我喜欢 table 每种类型,因为数据库是完全规范化的并且易于维护。我没有让继承的模型 ServiceCompany 与 Fluent API 一起工作。

基础摘要Class

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
[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; }
}

我在其中添加实体模型以使用 onModelCreating()

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

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

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

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

我希望能够用流利的语言做这样的事情API。

var ListofServiceCompanies = db.ServiceCompanies.All()

而不是这样

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

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

您可以通过调用 OfType 扩展方法来实现,如下所示:

var ListofServiceCompanies = db.Vendor.OfType<Vendor>().ToList();

或者您可以在 DbContext 中添加一个 DbSet<ServiceCompany> ServiceCompanies { get; set; },这样它看起来像这样:

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

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

    public DbSet<ServiceCompany> ServiceCompanies { get; set; }

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

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

然后拨打:

var ListofServiceCompanies = db.ServiceCompanies.ToList();