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

时间:2017-08-23 23:05:29

标签: entity-framework linq inheritance linq-to-entities

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

基础抽象类

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

我添加实体模型以使用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)

我更喜欢正确设置实体,使代码更好,更易于使用。任何见解或知识都表示赞赏。

1 个答案:

答案 0 :(得分:1)

您可以通过调用OfType扩展方法来执行此操作,如下所示:

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

或者您只需在DbSet<ServiceCompany> ServiceCompanies { get; set; }中添加DbContext即可,如下所示:

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();