Saturday, July 30, 2011

Using NHibernate Projections.Max in a Subquery

I found myself in the need of doing a Subquery in NHibernate recently that would fetch the max value of a column as the data I was working with was versioned.

The SQL that I needed to replicate was essentially the follow:

SELECT * 
FROM databaseTable
WHERE property = 'value'
AND version = (SELECT MAX(version) FROM databaseTable WHERE property = 'value')


After a bit of investigation I found the following solution:

using(var session = _database.OpenSession())
{
var detachedCriteria = DetachedCriteria.For(typeof(DatabaseRecord))
.Add(Restrictions.Eq("Property", value))
.SetProjection(Projections.Max("Version"));

var record = session.CreateCriteria(typeof (DatabaseRecord))
.Add(Restrictions.Eq("Property", value))
.Add(Subqueries.PropertyEq("Version", detachedCriteria))
.UniqueResult<DatabaseRecord>();

if (record == null)
throw new Exception("No records were found where Property = " + value);

return record;
}

No comments: