在 Linq 上按摘要加入 Table 组

Join Table Group By Summary On Linq

您好,我尝试将 SQL 查询转换为 LINQ。

SELECT C.ID, SUM(S.AMOUNT*CS.PRICE) AS TOTALCATEGORYSUMMARY 
FROM CATEGORY C 
INNER JOIN PRODUCT P ON P.CATEGORYID=C.ID 
INNER JOIN PSTOCK S ON S.PRODUCTID=P.ID 
INNER JOIN PCOST CS ON CS.PRODUCTID=P.ID 
GROUP BY C.ID

我尝试如下:

var qry = from c in categories
          join p in products on c.Id equals p.CategoryId
          join s in stoks on p.Id equals s.ProductId
          join t in costs on p.Id equals t.ProductId
          group new {c} by new { c.Name,s.Stock,t.Amount } into ct
          select (new { ct.Key.Name, AllCost=ct.Key.Amount * ct.Key.Stock });

我该怎么做?

根据您的 SQL 查询,您的 LINQ 语句应该是:

var qry = from c in categories
          join p in products on c.Id equals p.CategoryId
          join s in stoks on p.Id equals s.ProductId
          join t in costs on p.Id equals t.ProductId
          group new { c.Id, s.Amount, t.Price } by c.Id into ct
          select new { Id = ct.Key.Id, AllCost = ct.Sum(x => x.Amount * x.Price) };

参考文献

Group by single property

Enumerable.Sum method