NHibernate Forge
The official new home for the NHibernate for .NET community

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.

        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:

        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 may 15 2010, 10:49 p.m. by Tuna Toksoz


Hans Torm wrote re: Not So Hidden Gems of NHibernate – Formula Discriminators
on 06-03-2010 15:32

I had to do the same when mapping to our legacy database. Only I had to do a select from another table in the case statement to get the info needed for the discriminator.

I was impressed how easy it actually was to get working painlessly in NHibernate though.

Powered by Community Server (Commercial Edition), by Telligent Systems