Tim Scott's Blog

June 14, 2007

Ordering Computed Fields In ActiveRecord With ICriteria

Filed under: Active Record, C#, Castle Project — Tim Scott @ 11:48 pm

If you use ActiveRecord and ICriteria to fetch collections, this probably looks familiar:

DetachedCriteria criteria = DetachedCriteria.For(typeof(TaskEstimate));
...
criteria.AddOrder(Order.Asc("OptimisticHours"));
IList<TaskEstimate> estimates = TaskEstimate.FindAll(criteria);

The criteria object tells the FindAll method to sort the results ascending by the persisted property, “OptimisticHours.” But let’s say you have another persisted property “PessimisticHours,” and you want to sort by the difference between the optimistic and pessimistic estimates. That is to say, you want to sort by a computed value instead of a persisted property. Here’s how:

First you add the following to the TaskEstimate class:

private int _estimateDelta;
[Property(Formula = "PessimisticHours - OptimisticHours")]
public int EstimateDelta
{
    get { return _estimateDelta; }
    set { _estimateDelta= value; }
}

Then you can do this:

criteria.AddOrder(Order.Asc("EstimateDelta"));
IList<TaskEstimate> estimates = TaskEstimate.FindAll(criteria);

What’s happening here is that ActiveRecord is providing us access to the NHibernate mapping feature that allows you to define a property with a formula attribute.

Create a free website or blog at WordPress.com.