NHibernate mapping one table on two classes with where selection
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.
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.
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 N开发者_如何学运维Hibernate (or another library) can handle this.
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>
精彩评论