如何在Nhibernate中使用案例和顺序?

Art*_*m G 5 nhibernate hibernate case sql-order-by queryover

我需要在数据库表订购结果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
Run Code Online (Sandbox Code Playgroud)

那么,请你给我一个例子,说明如何创建这种结构.

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
Run Code Online (Sandbox Code Playgroud)

使用QueryOver.

Fel*_*ani 5

您可以使用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();
Run Code Online (Sandbox Code Playgroud)