如何将具有联接,组和内联查询的LINQ查询语法转换为LINQ方法语法

时间:2019-07-18 02:18:15

标签: c# linq-to-sql

我需要使用方法语法将SQL中的以下查询转换为LINQ,但是当我尝试包含内联查询,联接和分组时,我感到困惑:

SELECT CL.*, CB.*, CD.*, CC.*, CS.*
FROM clients AS CL
INNER JOIN (
    SELECT A.client_id, SUM(A.amount) AS balance
    FROM accounts AS A
    WHERE A.account_id = 1
    GROUP BY A.client_id
    HAVING (SUM(A.amount) > 0.015) OR (SUM(A.amount) < -0.015)
) AS CB ON CL.client_id = CB.client_id
INNER JOIN client_details AS CD ON (CL.client_id = CD.client_id) AND (CL.audit_id = CD.audit_id)
LEFT JOIN client_categories AS CC ON CD.client_category_id = CC.client_category_id
LEFT JOIN statuses AS CS ON CD.status_id = CS.status_id

我确实使GROUP BY和HAVING部分的工作独立于整体查询,但是我无法将其与其余部分合并为内联查询(尽管我已经尝试过.Any和其他LINQ方法):< / p>

.Where(a => a.AccountId == 1)
.GroupBy(a => new { a.ClientId })
.Where(ag => ag.Sum(a => a.Amount) > 0.015M || ag.Sum(a => a.Amount) < -0.015M)
.Select(ag => new { Id = ag.Key.ClientId, Balance = ag.Sum(a => a.Amount) })

我已经设法使用查询语法将其转换为LINQ,这对我来说非常合适,但是我需要在方法(Lambda)语法中使用它:

var clients = from c in _context.Clients
              join cb in (from a in _context.Accounts
                          where a.AccountId == 1
                          group a by new { Id = a.ClientId } into g
                          where g.Sum(gs => gs.Amount) > 0.015M || g.Sum(gs => gs.Amount) < -0.015M
                          select new { g.Key.Id, Balance = g.Sum(gs => gs.Amount) }) on c.Id equals cb.Id
              join cd in _context.ClientDetails on new { c.Id, c.AuditId } equals new { cd.Id, cd.AuditId }
              join cc in _context.ClientCategories on cd.ClientCategoryId equals cc.Id into ccj
              from cc in ccj.DefaultIfEmpty()
              join cs in _context.Statuses on cd.StatusId equals cs.Id into csj
              from cs in csj.DefaultIfEmpty()
              select new Client(c, cb.Balance, new ClientDetails(cd, cc, cs));

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

LinqPad似乎提供了解决方案。对数据库运行LINQ查询语法,完成后,单击页面底部的Lambda符号以查看方法语法:

LinqPad Window

感谢LinqPad!