views:

133

answers:

1

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.

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

alt text

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.

alt text

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.

+4  A: 

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

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>
Stefan Steinegger
Thanks! Works as expected.Would have been strange if it wasn't supported. This is one of things OR/M is made for.
Rene Schulte