2010-06-03 115 views
5

我們想用NHibernate在兩個類上映射單個表。映射必須根據列的值動態變化。NHibernate映射兩個類中的一個表與哪裏選擇

下面是一個簡單的例子,它使得它更清晰一些: 我們有一個名爲Person的表,其中列id,Name和Sex。

alt text

從該表中的數據應不管是在類男性或上取決於列性的值的類女性進行映射。

alt text

僞代碼:

create instance of Male with data from table Person where Person.Sex = 'm'; 
create instance of Female with data from table Person where Person.Sex = 'f'; 

的好處是我們強類型的域模型,並可以在以後避免switch語句。

這可能與NHibernate或者我們必須先映射Person表到一個扁平的Person類嗎?然後,我們將不得不使用自定義工廠方法,它需要一個扁平的Person實例並返回一個Female或Male實例。 如果NHibernate(或其他庫)可以處理這個問題,那將會很好。

回答

9

對於NHibernate來說,這是很常見的情況。您可以將整個類層次結構映射到一個表中。

您需要指定鑑別器值。

<class name="Person"> 
    <id .../> 

    <discriminator column="Sex" type="string" length="1" /> 

    <property name="Name"/> 
    <!-- add more Person-specific properties here --> 

    <subclass name="Male" discriminator-value="m"> 
    <!-- You could add Male-specific properties here. They 
    will be in the same table as well. Or just leave it empty. --> 
    </subclass> 

    <subclass name="Female" discriminator-value="f"> 
    <!-- You could add Female-specific properties here. They 
    will be in the same table as well. Or just leave it empty. --> 
    </subclass> 

</class> 
+0

謝謝!按預期工作。 如果不支持它會很奇怪。這是OR/M所做的一件事。 – 2010-06-03 13:00:11