The Dark Art of NHibernate

Ok so maybe it’s not a dark art: I just don’t have the book yet. It could be argued the book doesn’t exist yet, but now we’re getting sidetracked.

I was trying to write a DetachedCriteria for a type hierarchy and was stumbling hard. I have 3 classes NationalX, StateX, and OrganizationX that derive from a base type X. X is QualificationType, but I don’t really feel like typing that 50 million times (Does Live Writer needs intellisense?  :) )

I need to pull all X’s with State = state (type: StateX), Organization = organization (type: OrganizationX), and all records of type NationalX.

I got this far and hit a wall. This pulls out all the StateX’s and OrganizationX’s I’m interested in:

DetachedCriteria criteria = DetachedCriteria
     .For(typeof(QualificationType))
     .Add(Expression.Or(
              Expression.Eq("State", state),
              Expression.Eq("Organization", org)
              ));

Great!  I love NHibernate.  But how do I get those damn NationalX’s? There is no unique property in NationalX that is common across all the records I want aside from their type. I did not want to add a type property to my base, that seemed messy and a horrible idea.

Chris Bilson, god love him, saved my bacon. Every NHibernate entity has a Property you can query against, "class", that does pretty much exactly what you think it would.  I still can’t find any docs as to what this magical thing is really called. It’s probably in that damned book I don’t have. This is what I ended up with.

DetachedCriteria criteria = DetachedCriteria
    .For(typeof (QualificationType))
    .Add(Expression.Or(
             Expression.Or(
                 Expression.Eq("State", state),
                 Expression.Eq("class", typeof (NationalQualificationType))),
             Expression.Eq("Organization", org))
    );

This works, And how! I begin the descent into learning NHibernate.  Heaven help me.

PS- Expression.Or() should accept a paramarray.  That’d be hot.

Leave a Comment