猿问

低效的 LINQ - 知道 SQL 应该是什么 - 无法到达那里

我知道我想要生成的 SQL:


SELECT qdt, pbn, cid, pid, SUM(Amount) AS TotalAmount

FROM SomeDb.SomeTable

WHERE Status = 'Open'

GROUP BY cid, pid, qdt, pbn

ORDER BY qdt

我有 LINQ,我希望它能产生像上面的 SQL 一样干净的东西:


var query = (

  from someTable in SomeTable

  where someTable.Status == "Open"

  group someTable by new { someTable.cid, someTable.pid } into grouped

    select new

    {

      lid = grouped.FirstOrDefault().lid,

      qdt = grouped.FirstOrDefault().qdt,

      pbn = grouped.FirstOrDefault().pbn,

      cid = grouped.FirstOrDefault().cid,

      cn = grouped.FirstOrDefault().cn,

      pid = grouped.FirstOrDefault().pid,

      amount = grouped.Sum(o => o.Amount),

      Status = grouped.FirstOrDefault().Status

});

但这会产生许多令人讨厌的 SQL 行。对于 qdt,每个分组值最终都会在查询中获得自己的 SELECT 语句,如下所示:


SELECT [t5].[qdt]

FROM (

    SELECT TOP (1) [t4].[qdt]

    FROM [SomeDb].[SomeTable] AS [t4]

    WHERE ([t1].[cid] = [t4].[cid]) AND ([t1].[pid] = [t4].[pid]) AND ([t4].[Status] = @p0)

    ) AS [t5]

) AS [qdt]

有没有办法更改 LINQ 以生成更简单的 SQL?


HUX布斯
浏览 165回答 2
2回答
随时随地看视频慕课网APP
我要回答