views:

32

answers:

2

Dear ladies and sirs.

I have two tables - Run and Sample, where Sample.RunId is a foreign key linking samples to their runs.

I would like to have a SampleCount property in Run, which is the number of Sample objects associated with the particular Run.

Is it possible to map such a property in NHibernate mapping of the Run type?

Thanks.

+1  A: 

While you can do that using a <join>, it's not a good idea.

Instead, declare your Run.Samples collection as lazy="extra", and accessing Run.Samples.Count will do a query for the count instead of loading the entire collection.

Diego Mijelshon
Why is <join> a bad idea?
mark
<join> creates issues when updating, and you're also loading extra data on every access to Run. It's a hack to use it in this context (not that I haven't done it...)
Diego Mijelshon
+1  A: 

Although the collection solution by Diego Mijelshon is perfectly valid it does mean an extra query after fetching the Run entity. If you haven't mapped the collection and you do not want to or you do not want the additional query, consider a "computed" property as such

in the Run class mapping

<property name="SamplesCount" type="long" formula="(select count(s.Id) from Samples s where s.RunId = Id)" />

and in the class Run just add

long SamplesCount {get; set;}

Note that in the query, for the part "s.RunId = Id" NHibernate will insert the proper alias for the root table. Also, don't forget the parenthesis, it makes it easier for the parser and in some cases is required.

This approach has the benefit of applying a subquery on the select (which may or may not be good depending on your case). The property can also be lazily-loaded (i think a NH 2++ feature) if this property is something you will only rarely need.

Jaguar
Good one, I hadn't got formulas referencing the current entity right before. BTW, lazy-loaded properties are new to NH 3.x, so you can only use them now if you are willing to reference the trunk version.
Diego Mijelshon
Sounds great. I will definitely give it a try.
mark
interesting, in 2.1.2GA the mapping validates for property laziness although its not actually done
Jaguar