NHibernate Derived Properties
NHibernate dervied properties are calculated at runtime. I am building a demo project where I needed to calculate the sum of questions for a particular exam. My initial approach was to expose a readonly TotalPoint property in an exam object where the total points were calculated at runtime.
public double TotalPoint
{
get
{
double sum = 0.0;
IEnumerator<Question> enumerator = _questions.GetEnumerator();
while (enumerator.MoveNext())
{
sum += enumerator.Current.Point;
}
return sum;
}
}
This works great and had no problems. Later I used the dervied properties using NHibernate so I converted the code to the following:
public double TotalPoint
{
get
{
return _totalPoint;
}
The magic happens in the hibernate mapping file.
<
property name="
TotalPoint"
type="
Double"
access="
nosetter.camelcase-underscore"
formula="
(select SUM(q.Point) from Questions q where q.ExamID = ExamID)"
/> The above property belongs in the Exam.hbm.xml file. The formula attribute contains the SQL that will be executed when a TotalPoint is needed. Everything in the formula refers to the column names in the database and *not* the entity class.
This approach is good and crisp but it has problems of its own. It can only load the data if the data has been persisted. There are conditions when you don't want the TotalPoint of a persisted object but instead of the object present in memory waiting to be persisted. In that case the initial approach using C# code will work just fine. If you are only interested in calculations of a column where the data has been persisted then you should use derived properties.