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

Entity framework 将TPT继承的代码优先模型添加到Linq Fluent API,entity-framework,linq,inheritance,linq-to-entities,Entity Framework,Linq,Inheritance,Linq To Entities,我在将Fluent API扩展到继承类时遇到问题。我采用了TPT(每种类型的表)方法,并且每种类型的继承都有一个表。我喜欢每种类型的表,因为数据库完全规范化并且易于维护。我没有让继承的模型ServiceCompany使用Fluent API var ListofServiceCompanies = db.ServiceCompanies.All() 基抽象类 public abstract class Vendor { [Key] public int VendorID { g

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

var ListofServiceCompanies = db.ServiceCompanies.All()
基抽象类

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类

[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; }
}
而不是像这样

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

我更喜欢正确地设置实体,并使代码美观且易于使用。非常感谢您的洞察力和知识。

您可以通过调用如下扩展方法来实现这一点:

var ListofServiceCompanies = db.Vendor.OfType<Vendor>().ToList();
然后打电话:

var ListofServiceCompanies = db.ServiceCompanies.ToList();

关于为TPT(每种类型的表)继承设置Fluent API的详细说明
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();