2010-06-03 62 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

相关问题