標籤:
在前篇CodeFirst類型約定中,我們在資料庫中為每一個模型類建立一個表,但是有個問題,我們可以設計出帶繼承關係的模型類,即物件導向編程既有“has a”(表示類繼承)也有“is a”(表示類包含)關係,但是SQL的基礎關聯式模式在表與表中僅支援"has a"關係,SQL資料庫管理系統不支援繼承類型。所以,怎樣用關係型資料庫來映射物件導向模型呢?
Code-First中有下面三種不同的方法來表示一個繼承的階層:
- Table per Hierarchy (TPH): 這種方法建議用一張表來表示繼承階層,即這張表裡包含了兩個有繼承關係類的鑒別列。看如下代碼
public abstract class BillingDetail { public int BillingDetailId { get; set; } public string Owner { get; set; } public string Number { get; set; }} public class BankAccount : BillingDetail{ public string BankName { get; set; } public string Swift { get; set; }} public class CreditCard : BillingDetail{ public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; }} public class InheritanceMappingContext : DbContext{ public DbSet<BillingDetail> BillingDetails { get; set; }}View Code
BankAccount類和CreaditCard類都繼承於BillingDetail,在資料庫中會產生如下表:
在EF中這是預設的繼承映射層級結構
- Table per Type (TPT): 這個方法建議為每一個模型類寫一個分離的表。如所示:
代碼如下:
public abstract class BillingDetail{ public int BillingDetailId { get; set; } public string Owner { get; set; } public string Number { get; set; }} [Table("BankAccounts")]public class BankAccount : BillingDetail{ public string BankName { get; set; } public string Swift { get; set; }} [Table("CreditCards")]public class CreditCard : BillingDetail{ public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; }} public class InheritanceMappingContext : DbContext{ public DbSet<BillingDetail> BillingDetails { get; set; }}View Code
- Table per Concrete class (TPC): 這個方法建議除了抽象類別,一個實體類對應一個表。所以,如果有多個實體類繼承於抽象類別,抽象屬性將會成為每個實體類對應的表的一部分。如:
代碼:
public abstract class BillingDetail{ public int BillingDetailId { get; set; } public string Owner { get; set; } public string Number { get; set; }} public class BankAccount : BillingDetail{ public string BankName { get; set; } public string Swift { get; set; }} public class CreditCard : BillingDetail{ public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; }} public class InheritanceMappingContext : DbContext{ public DbSet<BillingDetail> BillingDetails { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<BankAccount>().Map(m => { m.MapInheritedProperties(); m.ToTable("BankAccounts"); }); modelBuilder.Entity<CreditCard>().Map(m => { m.MapInheritedProperties(); m.ToTable("CreditCards"); }); }}View Code
上面說的比較簡單,如果想要瞭解更多詳細資料,點擊下面的是三個連結:
- Inheritance with EF Code First: Table per Hierarchy (TPH)
- Inheritance with EF Code First: Table per Type (TPT)
- Inheritance with EF Code First: Table per Concrete class (TPC)
總結:這一節我也看得一知半解,如果有大神肯指點迷津,不勝感激。
EntityFramework Code-First 簡易教程(四)-------繼承策略