tags:

views:

89

answers:

2

I have two classes mapped in NHibernate: Dragon and its subclass FierceDragon, with a few FierceDragons stored stored in a table called Dragons. When I run an HQL query like from Dragon... I get back two objects per row: the expected FierceDragon and an ordinary Dragon that's a copy of the FierceDragon (insofar as is possible; naturally it lacks the FierceDragon's extra Ferocity and TimeSinceLastMeal properties). In particular, their IDs are identical. When I do from FierceDragon I get only FierceDragons, with no extra copies, but that won't work for me in general.

Why does this happen, and how can I prevent it?

A: 

The mystery is solved; I thought I was only mapping FierceDragon, but no, I was mapping Dragon too, both to the table Dragons. Not sure why NH did that particular thing in this case, but clearly the fix is to, you know, not map separate classes to the same table. Or if you do, at least give NH some way of distinguishing between the two in the DB.

David Seiler
+1  A: 

If you create your mapping correctly, that should not pose a problem. There are 3 different ways of mapping a class-hierarchy to the DB using NHibernate.

Check out this and this article.

You can map both Dragon and FierceDragon to the same table, but, in that case, your table should have some nullable columns to be able to store the additional properties of FierceDragon. Since you're talking about one table, I suppose you want to use the 'Table per class hierarchy' mapping strategy ?

Frederik Gheysels
No, I was using the 'map both classes without being aware of it' strategy. When I issued a query for Dragon, NH observed that Dragon and its subclass FierceDragon were mapped, and issued two select statements, one for each, blissfully unaware that they shared a table.
David Seiler