Tuesday, 2 October 2012

NHibernate: Filtering on Properties of Subtypes

Here's a useful tip I learned about NHibernate today. Say we have a task list, displaying details about entities of type Task. Various task types inherit from this. Once such type is 'ReviewDocumentTask'. This extends Task in that it has a reference to a Document entity. The base Task does not. The requirement is to filter out all tasks where the document has been deleted. How do we filter on this field, yet still treat tasks polmorphically? Two useful feature for this purpose are the ability to create an alias with a left outer join, and the ability to restrict on the 'class' property. The resulting code looks like this:
var result = SessionManager.Session
    .CreateAlias("Document", "document", JoinType.LeftOuterJoin)
            Restrictions.Eq("class", typeof(ReviewDocumentTask))
        Restrictions.Eq("document.Deleted", false))

return result.List<Task>();