摘要:在實體框架中我使用TPC創建兩個派生自相同基類的類。在流利的API中,我映射了繼承的屬性,但是如何建模基類的屬性?實體框架:TPC MapInheritedProperties模型超類屬性
更詳細的描述 在實體框架中我有一個類Child和兩種Children:一個男孩和一個女孩。男孩和女孩都來自孩子:
public class Child
{
public int Id {get; set;}
public string Name {get; set;}
}
public class Boy : Child
{
public string SomeBoyishProperty {get; set;}
}
public class Girl : Child
{
public string SomeGirlyProperty {get; set;}
}
我想要一個男孩和女孩的桌子,每張桌子也有孩子的屬性。
public class MyDbContext : DbContext
{
public DbSet<Boy> Boys {get; set;}
public DbSet<Girl> Girls {get; set;
}
From several sources, for example this one我才知道,這就是所謂的TPC:每個具體類,我應該MapInheritedProperties在OnModelCreating
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// model the properties of the base class, for instance set max length
modelBuilder.Entity<Child>()
.Property(p => p.Name).IsRequired().HasMaxLength(12);
// Model Daughter:
modelBuilder.Entity<Daughter>()
.Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Daughters");
})
.Property(p => p.SomeGirlyProperty).IsOptional().HasMaxLength(13);
// model Boy
modelBuilder.Entity<Son>()
.Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Sons");
})
.Property(p => p.SomeBoyishProperty).IsOptional().HasMaxLength(14);
}
表的SaveChanges過程中,我得到一個InvlidOperationException表明該主鍵不唯一。刪除構建孩子的部分解決了這個問題。
如何建立孩子屬性,而不必在女孩和男孩屬性中做到這一點?
是你的'兒童'在你的真實模型中抽象類? –
孩子摘要:我不打算創建兒童對象,只有男孩和女孩。我也不想創建一個Child表。所以如果我能幫助讓孩子抽象化,那麼我會這樣做。我當然可以讓一個男孩成爲一個孩子,這可以解決問題,但是對於我來說,一個男孩有一個孩子而不是一個孩子似乎有點奇怪 –