NHibernate将两个类的一个表映射到选择的位置

Ren*_*lte 5 .net mapping nhibernate orm nhibernate-mapping

我们想用NHibernate在两个类上映射一个表.映射必须根据列的值动态生成.

这是一个简单的例子,使它更清晰:我们有一个名为Person的表,其中列为id,Name和Sex.

替代文字

此表中的数据应映射到Male类或Female类,具体取决于Sex列的值.

替代文字

在伪代码中:

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'; 
Run Code Online (Sandbox Code Playgroud)

好处是我们有强类型域模型,以后可以避免切换语句.

NHibernate可以实现这一点,还是我们必须先将Person表映射到一个扁平的Person类?然后我们将不得不使用一个自定义工厂方法,该方法采用一个平坦的Person实例并返回一个Female或Male实例.如果NHibernate(或其他库)可以处理这个问题会很好.

Ste*_*ger 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>
Run Code Online (Sandbox Code Playgroud)