Fluent NHibernate, Counting Entries In A Related Table

I have a simple Fluent NHibernate mapping setup where a parent table has a ‘HasMany’ relationship to the child table.

As part of the parent table, I want to include a property that indicates how many child entries there are, without having to map the child relationship. This is mainly because I don’t want the additional overhead of bringing back each child record, but is also useful for being able to sort by the count.

Turns out this can be achieved quite easily by using the ‘Formula’ function on a mapped property:

Map(c => c.ChildCount).Formula("(select count(*) from childTable where childTable.parentId = id)");

Simple when you know how!