C# – Partially Populate Child Collection with NHibernate


I've been struggling with this for a while, and can't seem to figure it out…

I've got a BlogPost class, which has a collection of Comments, and each of the comments has a DatePosted field.

What I need to do is query for a BlogPost and return it with a partially loaded Comments collection, say all comments posted on the 1 Aug 2009.

I've got this query:

BlogPost post = session.CreateCriteria<BlogPost>()
    .Add(Restrictions.Eq("Id", 1))
    .CreateAlias("Comments", "c")
    .Add(Restrictions.Eq("c.DatePosted", new DateTime(2009, 8, 1)))

When I run this query and check out the generated sql, it first runs a query against the BlogPost table, joining to the Comment table with the correct date restriction in, then runs a second query just on the Comment table that returns everything.

Result is the Comments collection of the BlogPost class totally filled up!

What am I doing wrong?

I've got code samples if anyone needs more info…!

Best Answer

There is a result transformer for this, see the documentation.


Note that the kittens collections held by the Cat instances returned by the previous two queries are not pre-filtered by the criteria! If you wish to retrieve just the kittens that match the criteria, you must use SetResultTransformer(CriteriaUtil.AliasToEntityMap).

IList cats =
    .CreateCriteria("Kittens", "kt")
        .Add( Expression.Eq("Name", "F%") )

You could also use filters that get activated using session.EnableFilter(name).

There is a similar question here.