Monday, May 17, 2010

Not So Hidden Gems of NHibernate – Formula Discriminators

A friend of mine, Cristian Prieto, told me that he didn’t know how to do mapping of some entities to (in his terms) an evil legacy database.

There were two entities: Advertiser and Affiliate. As I said, this was a crazy legacy database. Both shares the same table with only one difference: If an entity is Affiliate, then it’s affiliate_id column will have a value, otherwise, a non-empty advertiser_id means it’s an Advertiser. Both cannot be the same at the same time.

Having gone through NHibernate code a while ago, I remember being able to discriminate on an expression (or in NH terms: Formula). I wasn’t sure about it, but Cristian verified that there is such thing that exists, and you can use it for such thing.

Here is the description of formula discriminator from the documentation.

view plaincopy to clipboardprint?
<discriminator  
       column="discriminator_column"    
       type="discriminator_type"        
       force="true|false"              
       insert="true|false"              
       formula="arbitrary SQL expression"  
/>  

formula (optional) an arbitrary SQL expression that is executed when a type has to be evaluated. Allows content-based discrimination

Read more: Tuna Toksoz

Posted via email from jasper22's posterous