2017-08-23 11 views
0

我在将Fluent API扩展到继承类时遇到了问题。我采用了TPT(table per type)方法,并且每种类型的继承都有一个表。我喜欢每种类型的表格,因为数据库完全标准化并易于维护。我没有得到继承的模型ServiceCompany与Fluent API一起工作。将TPT继承代码第一个模型添加到Linq 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类从供应商

当我加入了实体模型,以便能够与onModelCreating()的流畅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

你可以通过调用像下面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(); 
+0

为T设置Fluent API的很好的解释PT(Table per Type)继承 – dev8989