将包含GROUP BY的SQL Server查询转换为NHibernate LINQ

时间:2015-11-26 12:28:07

标签: sql-server linq nhibernate linq-to-nhibernate

我基本上是在尝试检索按(行)创建日期排序的唯一GUID的分页列表。

我已经能够根据this answer起草一个似乎对我有用的SQL Server查询,但现在我必须将其转换为LINQ。

SELECT TOP 15 payment.ClientRef, 
          MAX(payment.CreatedDateUtc)
FROM PaymentTransactionState payment
INNER JOIN OrderState orderstate ON payment.ClientRef = orderstate.ClientRef
WHERE orderstate.UserId = 2 AND 
      payment.PaymentState IN (
        'Rejected',
        'Authorized') 
GROUP BY payment.ClientRef
ORDER BY MAX(payment.CreatedDateUtc) DESC,
         payment.ClientRef

问题是,我不能在IQueryOver上应用GroupBy,我可能错过了合适的语法:

session
    .QueryOver<Payment>()
    .JoinAlias(orderState => orderState.OrderStateEntity, () => orderStateRow)
    .Where(() => orderStateRow.UserId == customer.UserId)
    .WhereRestrictionOn(payment => payment.PaymentState).IsIn(paymentStates)
    .GroupBy(pts => pts.ClientRef)
    .OrderBy(payment => payment.CreatedDateUtc).Desc
    .Skip(pageIndex*pageSize)
    .Take(pageSize)
    .List();

我可以在查询语法中执行该组,但我不太确定Skip&amp;点点滴滴。

2 个答案:

答案 0 :(得分:0)

我会这样试试:

var query = db.PaymentTransactionState 
  .Where( pts => pts.OrderState.UserId == 2 &&
                 new string[] {"Rejected", "Authorized"}.Contains(pts.PaymentState) )
  .GroupBy( pts => pts.ClientRef )
  .OrderByDescending( pts => pts.Max( p => p.CreatedDateUtc))
  .ThenBy( p => p.Key )
  .Take(15);

答案 1 :(得分:-1)

所以这对我有用:基本上我必须使用SelectList而不是GroupBy; SelectGroup,SelectMax&amp;一旦我发现,转换就很容易解决;

PaymentRow paymentAlias = null;
OrderStateRow orderStateRow = null;

var transactionStateRows = session
    .QueryOver<PaymentRow >()
    .JoinAlias(orderState => orderState.OrderStateEntity, () => orderStateRow)
    .Where(() => orderStateRow.UserId == customer.UserId)
    .WhereRestrictionOn(payment => payment.PaymentState).IsIn(paymentStates)
    .SelectList(list => list
        .SelectGroup(payment => payment.ClientRef).WithAlias(() => paymentAlias.ClientRef)
        .SelectMax(payment => payment.CreatedDateUtc).WithAlias(() => paymentAlias.CreatedDateUtc))
    .TransformUsing(Transformers.AliasToBean<PaymentRow >())
    .OrderBy(payment => payment.CreatedDateUtc).Desc
    .Skip(pageIndex*pageSize)
    .Take(pageSize)
    .List();

我会留在这里,万一有人可能会发现我的艰辛在将来有用。谢谢你的回复。