Search code examples
nhibernatefluent-nhibernate-mapping

Handle cases where Nhibernate subclass does not exist


I have a scenario where I am using nhibernate to map records from one table to several different derived classes based on a discriminator.

public class BaseClass { }

public class DerivedClass0 : BaseClass { }
public class DerivedClass1 : BaseClass { }
public class DerivedClass2 : BaseClass { }

I then use nhibernate's DiscriminateSubClassesOnColumn() method and alter the configuration to include

<subclass name="DerivedClass0" extends="BaseClass" discriminator-value="discriminator0" />
<subclass name="DerivedClass1" extends="BaseClass" discriminator-value="discriminator1" />
<subclass name="DerivedClass2" extends="BaseClass" discriminator-value="discriminator2" />

so that when mapped, these classes are cast to their derived classes and not BaseClass.

However, there are some records in my database which have a discriminator which does not have a corresponding subclass. In these cases, nHibernate throws an error:

"Object with id: 'xxx' was not of the specified subclass..."

Is there some way I can handle this, so that any records which do not have a corresponding subclass are cast to BaseClass rather than an error being thrown?

I have simplified the above as much as possible, however it is worth noting that the XML is edited dynamically which is why I am referencing fluent nhibernate [DiscriminateSubClassesOnColumn()] and XML at the same time.

The following things (which would help) are not an option:

  • I cannot correct the data to remove records which are invalid
  • I cannot create subclasses for those records which do not have one

I need to handle cases where nHibernate tries to map on a discriminator and finds that one does not exist.


Solution

  • The solution is to use the "AlwaysSelectWithValue()" method in the Fluent NHibernate mapping.

    DiscriminateSubClassesOnColumn("discriminator").AlwaysSelectWithValue();
    

    This forces NHIbernate to only fetch results from the database which have a corresponding subclass.