Logo

NHibernate

The object-relational mapper for .NET

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.

<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

Bingo! “an arbitrary sql expression” is just what we wanted.

Going back to Cristian’s problem, we can now use this:

<discriminator 
        type="Int32" 
        formula="(case when not affiliate_id is null then 0 else 1 end)"
/>

The rest is left as an exercise for the reader (I always wanted to say this!)


Posted Sat, 15 May 2010 11:49:53 AM by tehlike
Filed under:

comments powered by Disqus
© NHibernate Community 2024