Joseph Nields
Joseph Nields

Reputation: 5661

How to get projected property in NHibernate?

Let's say I am using NHibernate and want to find some aggregate values of a set. I have something like this:

var crit = session.CreateCriteria<T>();
crit.Add(someRestrictions);
crit.SetProjection(
    Projections.ProjectionList()
        .Add(Projections.Min(propertyName), "min" + propertyName)
        .Add(Projections.Max(propertyName), "max" + propertyName)
);
var ur = crit.UniqueResult();
var min = ???
var max = ???

How do I get the value for min and max?

Upvotes: 2

Views: 694

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

The usual way is to create some DTO:

public class MyDto
{
    public virtual int MinProperty { get; set; }
    public virtual int MaxProperty { get; set; }
}

And this could be the resulting query:

var result = crit.SetProjection(
    Projections.ProjectionList()
        .Add(Projections.Min(propertyName), "MinProperty") // "min" + propertyName)
        .Add(Projections.Max(propertyName), "MaxProperty") // "max" + propertyName)
    )
    .SetResultTransformer(Transformers.AliasToBean<MyDto>())
    .UniqueResult<MyDto>();

Which will return a MyDto with typed access to min and max properties

Upvotes: 2

Related Questions