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 05-15-2010 11:49 PM by Tuna Toksoz

[Advertisement]

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)