2015-11-26 83 views
-1

我基本上試圖檢索按(行)創建日期排序的獨特GUID的分頁列表。將包含GROUP BY的SQL Server查詢轉換爲NHibernate LINQ

我已經能夠起草一個基於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(); 

我大概可以在查詢語法做組,但我米不太確定跳過&需要一點。

+0

您應該指定您希望使用的Linq提供程序;例如linq-to-sql或實體框架。要麼涉及構建映射到數據庫表的一組類,並通過它來構建Linq查詢。 –

+0

你有試過自己翻譯嗎?你面臨什麼問題? –

+0

我忘了提及:NHibernate;我用我正面臨的確切挑戰更新了故事 –

回答

-1

所以這裏是爲我工作:基本上我不得不使用的SelectList代替的GroupBy; SelectGroup,SelectMax & TransformUsing很容易解決,一旦我發現;

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(); 

我會在這裏留下以防萬一有人會發現我的辛勞將來會有用。謝謝您的回覆。

+0

此代碼幾乎無法維護。 ORM不是SQL的替代品。它們旨在使映射表更容易實體化。在這種情況下,不存在實體或表格。這是一個報告方案,它不是用來和ORM一起使用的。只需使用原始查詢。 –

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);