NHibernate mapping one table on two classes with where selection

Posted by Rene Schulte on Stack Overflow See other posts from Stack Overflow or by Rene Schulte
Published on 2010-06-03T09:27:58Z Indexed on 2010/06/03 9:34 UTC
Read the original article Hit count: 352

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.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about nhibernate