Как использовать case и order by в Nhibernate? - PullRequest
5 голосов
/ 17 декабря 2011

Мне нужно упорядочить результат в таблице БД ChargeOperations в в моем собственном направлении на typeId.Запрос SQL выглядит следующим образом:

SELECT * FROM ChargeOperations co
LEFT JOIN ShadowChargeOperations sco ON sco.ChargeOperationId=co.Id
-- just exclude some extra data.
WHERE sco.Id IS NULL
ORDER BY
 CASE co.TypeId
  WHEN 1 THEN 3   -- this is my order, which is different from id of type and can change
  WHEN 2 THEN 1
  WHEN 3 THEN 2
  ELSE 4
 END,
 co.TypeId,
 co.CalculationAmount

Итак, не могли бы вы дать мне пример того, как я могу создать эту конструкцию.

CASE co.TypeId 
  WHEN 1 THEN 3   -- this is my order, which is different from id of type and can change
  WHEN 2 THEN 1
  WHEN 3 THEN 2
  ELSE 4

с помощью QueryOver.

1 Ответ

3 голосов
/ 19 февраля 2015

Вы можете сделать это, используя Projections.Conditional, например:

ChargeOperation itemAlias = null;

var result = 
    session.QueryOver<ChargeOperation>(() => itemAlias)
            .Where ( /*your conditions*/)
            .OrderBy(Projections.Conditional(
                        Restrictions.Where(() => itemAlias.TypeId == 1),
                        Projections.Constant(3),                                
                    Projections.Conditional(
                        Restrictions.Where(() => itemAlias.TypeId == 2),
                        Projections.Constant(1),
                    Projections.Conditional(
                        Restrictions.Where(() => itemAlias.TypeId == 3),
                        Projections.Constant(2),
                        )
                    )           
                )                           
            ).Asc
            .ThenBy(x => x.TypeId)
            .ThenBy(x => x.CalculationAmount)
        .List();
...