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

时间:2022-12-22 11:28:02

We would like to map a single table on two classes with NHibernate. The mapping has to be dynamically depending on the value of a column.

我们想用NHibernate在两个类上映射一个表。映射必须动态地依赖于列的值。

Here's a simple example to make it a bit clearer: We have a table called Person with the columns id, Name and Sex.

这里有一个简单的示例,让它更清楚一些:我们有一个名为Person的表,其中包含id、名称和性别。

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

The data from this table should be mapped either on the class Male or on the class Female depending on the value of the column Sex.

该表中的数据应该根据列性别的值映射到类Male或类Female上。

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

In Pseudocode:

在伪代码:

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'; 

The benefit is we have strongly typed domain models and can later avoid switch statements.

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

Is this possible with NHibernate or do we have to map the Person table into a flat Person class first? Then afterwards we would have to use a custom factory method that takes a flat Person instance and returns a Female or Male instance. Would be good if NHibernate (or another library) can handle this.

对于NHibernate,这可能吗?还是我们必须首先将Person表映射到flat Person类?然后,我们将不得不使用一个定制的工厂方法,它采用一个扁平的Person实例并返回一个女性或男性实例。如果NHibernate(或其他库)能够处理这个问题,那就太好了。

1 个解决方案

#1


9  

This is quite a common case for NHibernate. You can map whole class hierarchies into a single table.

这是NHibernate很常见的情况。您可以将整个类层次结构映射到单个表中。

You need to specify a discriminator value.

您需要指定鉴别器值。

<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>

#1


9  

This is quite a common case for NHibernate. You can map whole class hierarchies into a single table.

这是NHibernate很常见的情况。您可以将整个类层次结构映射到单个表中。

You need to specify a discriminator value.

您需要指定鉴别器值。

<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>