0

我正在使用两个表:CI_CLIENTRISK(SCD 类型 2)...和 ​​QB_INVOICES_HEADER(edmx screenshot)。

它们可以通过 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));
        }
4

2 回答 2

1

试着把你的.Take(50)方法放在你的决赛之后.Select和之前.ToList()。实际上,您只获取第一个表的前 50 条记录,然后从那里加入。我假设在第一个表的前 50 条记录中没有连接到第二个表;因此,您的结果将有 0 条记录。

于 2012-10-27T01:12:33.923 回答
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();
于 2012-10-27T02:01:31.453 回答