2012-10-27 84 views
0

我正在處理兩個表:CI_CLIENTRISK(SCD類型2)...和QB_INVOICES_HEADER(edmx screenshot)。以linq方法語法連接兩個表,MVC EntityFramework

它們可以通過ClientID連接。我想實質上覆制此查詢:

SELECT a.ClientID, 
    MAX(b.InvoiceDt) AS MaxInvoiceDt 
    (omitted for brevity) 
FROM CI_CLIENTRISKADJS a 
INNER JOIN QB_INVOICES_HEADER b 
ON a.ClientID = b.ClientID 
WHERE a.IsActive = 1 
GROUP BY a.ClientID 
ORDER BY MaxInvoiceDt DESC 

這是我到目前爲止。它沒有返回任何記錄。

using (var db = new PLOGITENS01Entities()) 
     { 
     var rvClientRiskAdjs = db.CI_CLIENTRISKADJS 
      .Take(50) 
      .Join(db.QB_INVOICES_HEADER, 
       a => a.ClientID, 
       b => b.ClientID, 
       (a, b) => new { Risk = a, Invoices = b }) 
      .Where(a => a.Risk.IsActive == 1) 
      .OrderByDescending(o => o.Invoices.InvoiceDt) 
      .Select(c => new ClientRiskModel() 
      { 
       ClientRiskId = c.Risk.ClientRiskID, 
       ClientName = c.Risk.CI_CLIENTLIST.ClientName, 
       ClientId = c.Risk.ClientID, 
       ClientRiskAdjs = c.Risk.ClientRiskAdjs, 
       RecordValidStartDt = c.Risk.RecordValidStartDt, 
       RecordValidEnddt = c.Risk.RecordValidEnddt, 
       IsActive = c.Risk.IsActive 
      }) 
      .ToList(); 

     return View(new GridModel(rvClientRiskAdjs)); 
     } 

回答

0

我碰到這種解決方案偶然從閱讀這篇文章:https://stackoverflow.com/a/157919/1689144

var rvClientRiskAdjs = (from ri in db.CI_CLIENTRISKADJS 
         join qb in 
          (from qb in db.QB_INVOICES_HEADER 
          orderby qb.InvoiceDt ascending 
          group qb by qb.ClientID into grp 
          select new 
          { 
           InvoiceDt = grp.Max(s => s.InvoiceDt), 
           ClientID = grp.Key 
          }) 
         on ri.ClientID equals qb.ClientID 
         orderby qb.InvoiceDt descending 
         where ri.IsActive == 1 
         select new ClientRiskModel() 
         { 
          ClientRiskId = ri.ClientRiskID, 
          ClientName = ri.CI_CLIENTLIST.ClientName, 
          ClientId = ri.ClientID, 
          ClientRiskAdjs = ri.ClientRiskAdjs, 
          RecordValidEnddt = ri.RecordValidEnddt, 
          RecordValidStartDt = ri.RecordValidStartDt 
         }) 
         .ToList(); 
1

嘗試把你的.Take(50)方法之後.ToList()最終.Select之前。事實上,你只是拿走第一張桌子的前50個記錄,然後從那裏加入。我假設在第一個表的前50個記錄中沒有連接到第二個表;因此,你的結果將有0條記錄。

+0

謝謝你的提示。 :)這是有效的,但它沒有考慮最大聚合(在SQL查詢的第二行中找到)。它返回所有客戶端ID和沒有組的列表。我最終偶然發現了這篇文章的答案:http://stackoverflow.com/a/157919/1689144 – Kyle