Home >

Not So Hidden Gems of NHibernate – Formula Discriminators

13. July 2010

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!)

Comments

3/21/2011 10:59:04 PM #
Love your site Smile
3/22/2011 10:52:13 AM #
Apple now has Rhapsody as an app, which is a great start, but it is currently hampered by the inability to store locally on your iPod, and has a dismal 64kbps bit rate. If this changes, then it will somewhat negate this advantage for the Zune, but the 10 songs per month will still be a big plus in Zune Pass' favor.
3/22/2011 6:19:42 PM #
Great article! So happy to finally see a decent post about tis topic.  I will bookmark it so that I may come back and read more.
Comments are closed