Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate sorting (SQL as a second option)

I'm using NHibernate as my ORM and I'm trying to sort some data. The data needs to be retrieved paged.

Two of the columns in my Request table are UrgencyID and CreateDate. UrgencyID is a FK to the Urgency table with static data: 1 = Low, 2 = Normal, 3 = High, 4 = Critical.

I need to order my Requests in the following manner. Critical Requests by CreateDate descending All other requests by CreateDate descending

So my list of Requests should always have Critical by CreateDate desc at the top and then all other Requests (disregarding UrgencyID) by CreateDate desc

Is it possible to perform this sort order in NHibernate (using the Criteria API)?

If not, how would I do this in SQL? In a stored procedure?

EDIT: Solution thanks to both @DanP and @Michael Pakhantsov

Using the this_ prefix in the sql string as this is the default NHibernate prefix for the primary table selection.

public class OperatorJobQueueOrder : Order
    {
        public OperatorJobQueueOrder() : base("", true) { }
        public override NHibernate.SqlCommand.SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
        {
            return new NHibernate.SqlCommand.SqlString("case this_.JobRequestUrgencyID when 4 then 4 else 0 end desc, this_.CreatedDate");
        }
    }
like image 479
Ciaran O'Neill Avatar asked Sep 16 '25 00:09

Ciaran O'Neill


1 Answers

You may be able to create a custom sort order to handle this through the critiera api; see this question for an example implementation.

like image 50
DanP Avatar answered Sep 17 '25 15:09

DanP