Search code examples
nhibernatesql-order-bynhibernate-criteria

NHibernate Criteria API - order by max of two properties


I have a PrivateMessage class and I want to get list of PMs for user sorted chronologically either by CreationDate or LastAnswerDate (depending on which is more recent) using Criteria API.

How to sort by max of these two properies in Criteria API? My code looks similar to following:

var dc = DetachedCriteria.For<PrivateMessage>();
...
dc.AddOrder(new Order("???");
return (IList<PrivateMessage>)FindAll(typeof(PrivateMessage), dc);

CreationDate is DateTime and LastAnswerDate is DateTime?.

Thanks!


Solution

  • Order.Desc(
        Projections.Conditional(
            Restrictions.GtProperty("CreationDate", "LastAnswerDate"),
            Projections.Property("CreationDate"),
            Projections.Property("LastAnswerDate"))))