colinramsay.co.uk

NHibernate's Polymorphism

21 Jan 2007

I've got a fairly complex database structure for a project I'm working on, and I was trying to work out how to query for what I needed. I'm using Active Record, which uses NHibernate underneath.

I spotted this in the "polymorphic queries" section of the HQL docs (for Java, think C#):

"Hibernate queries may name any Java class or interface in the from clause."

Well, awesome. This means that given the correct database schema, I can query for objects which implement a particular interface - in my case INewsworthy. A quick search came up with some sample code for doing this, though if you're using Active Record you need to get hold of an ISession first.
String id = 'xxx';

IResearchItemDatumParent parent =
session.CreateCriteria(typeof(IResearchItemDatumParent))
.Add(Expression.Eq("ID", id))
.UniqueResult<iresearchitemdatumparent>();

After adapting this to suit my needs, I was left with three lines of code that did something pretty incredible in an extremely elegant manner.