Search code examples
c#nhibernatenhibernate-criteria

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?


Solution

  • 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