Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

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.

Published Thursday, September 20, 2007 4:30 PM by azamsharp

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: NHibernate Derived Properties @ Saturday, September 22, 2007 10:53 AM

In the first example you'd have to be careful because you may *only* want to return the total, but not bear the burden of going to the database to load all the exams. Your second example avoids this issue.

Ben Scheirman

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below