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

时间:2011-12-17 09:36:30

标签: hibernate nhibernate sql-order-by case 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

那么,拜托,您能举例说明如何创建这种结构。

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 个答案:

答案 0 :(得分:3)

您可以使用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();