colinramsay.co.uk

NHibernate - Querying with Criteria

20 Jan 2008

I don't find the NHibernate documentation to be that useful for anything more than the basics. When querying through an association (which you'll probably do a lot), I found there are different ways of achieving the same result. Using a blog as an example, I can query for Posts in a particular Category like this:

DetachedCriteria criteria = DetachedCriteria.For<Post>()
	.CreateCriteria("Category")
	.Add(Expression.Eq("CategoryID", 55));

When I first started using NHibernate in earnest, I saw CreateCriteria as a way of "drilling down" into the association, in this case the Category property on a Post. After that I can then add a constraint on the Categories which will affect the Posts which are returned. This is indeed the way it works, and the above approach returns what I'd expect. However, the same result can be achieved like this:

DetachedCriteria criteria1 = DetachedCriteria.For<Post>()
	.Add(Expression.Eq("Category.CategoryID", 55));

This is perhaps more intuitive for some, though it wasn't how I approached the problem. Both methods return the same result set, but there is one important difference. When you look at the generated SQL for each approach, the first method, drilling down via CreateCriteria, includes all of the columns for the Category entity, and so in this example you're selecting more data than you need to.

Chaining with CreateCriteria allows you to return data from multiple entities/tables, but for a simple query like I've shown, it's not the correct approach.