NHibernate maps one table to two classes, where the choice

We would like to display one table in two classes with NHibernate. The display should be dynamically dependent on the column value.

Here is a simple example to make it clearer: We have a table called Person with the column identifiers, Name and Sex.

alt text

Data from this table should be displayed in either the Male class or the Female class, depending on the value of the Sex column.

alt text

In pseudo code:

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 advantage is that we strictly typed domain models and can later avoid switch statements.

Is this possible with NHibernate, or do we need to first map the Person table to a flat Person class? Then after that we will have to use our own factory method, which takes a flat instance of Person and returns an instance of Female or Male. It would be nice if NHibernate (or another library) can handle this.

+5
source share
1 answer

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

You need to specify the 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>
+9
source

All Articles