Tuesday 5 July 2011

How to make NHibernate ignore rows with an incorrect discriminator for an association subclass

If you are mapping a class hierarchy to a single table in NHibernate by using a discriminator column to differentiate between the subclasses, if one of the concrete subclasses is being used as an association for another type you might run into the situation where incorrect data (i.e. discriminator value) in the database causes NHibernate to throw an exception complaining that it cannot find the class. (This can also happen if you are using the where attribute to exclude a reserved entity from being picked up.) The default behaviour is to throw an NHibernate.ObjectNotFoundException exception on accessing a row that cannot be mapped to the expected entity. Alternatively you can tell NHibernate to ignore this situation and substitute a null value for the missing association.
You do this by setting the not-found attribute of the many-to-one element to "ignore”. For example:

<many-to-one class="Engineer" column="EngineerID" name="Engineer" not-found="ignore"></many-to-one>

No comments:

Post a Comment