Showing posts with label NHibernate. Show all posts
Showing posts with label NHibernate. Show all posts

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>

Friday, 29 April 2011

Lack of NHibernate HQL support for question mark character in column name

If you’re faced with a database that contains reserved characters in some of its column names, NHibernate allows you to escape a column name in the mapping file by wrapping the column name in backticks, for example:

<class name="Foo">
   <property name="Bar" column="`Bar?`" />
</class>


This convention is used by NHibernate to generate SQL with the column name wrapped appropriately (e.g. [] for SQL Server). This works as intended for ICriteria queries and for HQL queries returning tuples in the following form:

session.CreateQuery("select Bar from Foo").List();

For SQL Server this results in the following SQL:

select foo0_.[Bar?] as col_0_0_
from Foo foo0_


The problem occurs if you use the entity selection form of the HQL query in conjunction with the generic List method:

session.CreateQuery("select foo from Foo foo").List<Foo>();

In this scenario, when constructing the SQL statement NHibernate interprets the question mark as a position parameter placeholder and substitutes the question mark with the parameter, i.e. the query winds up containing this column

foo0_.[Bar@p0]

instead of

foo0_.[Bar?]

Unfortunately this is a fault in NHibernate 3.1:

http://stackoverflow.com/questions/5805617/escaping-a-question-mark-character-in-a-column-name-in-nhibernate