2012-04-04 41 views
1
一些屬性值的基礎上,兩個表中的一個表

假設我有一個基類組件和兩個派生類ComponentA和以componentB,類似如下:選擇在MVC3和EF

public class Component 
{ 
    public int ComponentID {get; set;} 
    public int ComponentType {get; set;} 
    // some other statements ... 
} 

然後

public class ComponentA : Component 
{ 
    // some statements ... 
} 

public class ComponentB : Component 
{ 
    // some statements ... 
} 

現在,基於組件類中COmponentType的值,如何切換到ComponentA或ComponentB並檢索其相關數據。

這是在edmx中如何做到這一點的示例之一,但我想知道是否有任何方法可以在EF的Code First方法中做同樣的事情。 http://www.c-sharpcorner.com/UploadFile/ff2f08/entity-framework-4-0-tph-part-2/

回答

0

可以發現TPH(每層次結構表)與代碼第一here

0

可以刪除ComponentType屬性和EF將自動創建Component表與用於區分(杜)一個Discriminator列之間子類。

如果你需要一個特定的列名和/或數據類型鑑別列,您可以覆蓋默認值在OnModelCreating事件您DbContext的,無論是直接或通過EntityTypeConfiguration例如通過做

Map(m => m.Requires("ComponentType").HasValue(1); 

爲每個子類型。 (HasValue顯然每次都有不同的值)。

您將在上下文中創建一個屬性DbSet<Component>。這將返回所有組件,不論類型如何。如果你只是想ComponentA就做

context.Components.OfType<ComponentA>(). ... 

哦,Component應該是一個抽象類。