在前篇CodeFirst類型約定中,咱們在數據庫中爲每個模型類建立一個表,可是有個問題,咱們能夠設計出帶繼承關係的模型類,即面向對象編程既有「has a」(表示類繼承)也有「is a」(表示類包含)關係,可是SQL的基礎關係模型在表與表中僅支持"has a"關係,SQL數據庫管理系統不支持繼承類型。因此,怎樣用關係型數據庫來映射面向對象模型呢?html
Code-First中有下面三種不一樣的方法來表示一個繼承的層次結構:web
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; } }
BankAccount類和CreaditCard類都繼承於BillingDetail,在數據庫中會生成以下表:數據庫
在EF中這是默認的繼承映射層級結構編程
代碼以下:app
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; } }
代碼:asp.net
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"); }); } }
上面說的比較簡單,若是想要了解更多詳細信息,點擊下面的是三個連接:ide
總結:這一節我也看得只知其一;不知其二,若是有大神肯指點迷津,不勝感激。ui