I have an NHibernate mapping problem that does not seem easy to solve, to me.
Names Table
- Id (native, primary key) (int)
- entity_type (var char) (designates related table)
- entity_id (int) (foreign key (kinda) to various tables, based on entity_type)
- first_name
- last_name
- other columns
People Table
- Id (native, primary key) (int)
- birthday
- other columns
When names.entity_type = 'people' then names.entity_id = people.id
I have tried various scenarios, which are either incredibly ugly hacks or just fall short of what NHibernate can do.
The nicest one I have come up with (but can't get to work) is to use the join mapping, where you join the columns of Names table with People table into a single object, something like this:
class Person {
int Id { get; set; }
Date Birthday { get; set; }
string FirstName { get; set; }
string LastName {get; set; }
... bunch of other properties.
}
The mapping file goes something like this:
<class name="Person" table="people">
<id name="Id"><generator class="native"/></id>
<property name="Birthday"/>
<join table="names">
<key column="entity_id"/>
<property name="FirstName" column="first_name"/>
<property name="LastName" column="last_name"/>
</join>
</class>
The problem is that I can not figure out how to include the entity_type to the equation. This mapping works fine just as long as we only have one entity_type, so there is no fear of id clashes. There appears to be no way (?) I can tell NHibernate to add
and entity_type='people'
to the query in terms of the mapping. I can define more than one column in the key mapping but the parent table has to have two columns in this case (which it does not have).
I can get the mapping to work by using collections and incredibly ugly classes. This is technically one-to-one mapping but the problem is that the parent (people table) generates the ID, and so, the one-to-one mapping has to be on the names table side, which does not work (would need something like Name.Person relationship).
I can't change any aspect of the database!
Any help is appreciated - I have a feeling I am looking at this the wrong way and just can't see the solution.