Linq的实体左连接+分组+总和

时间:2012-06-11 08:42:43

标签: linq join entity sum

SQL查询(执行计划成本= 0.0127553)

SELECT 
 SUM(DATEDIFF(second, DTActivate, DTDeActivate)) AS Seconds,
 AA.ID AS AAID,
 AA.WorkStation
FROM 
 DbLogItems I 
INNER JOIN DbApplicationArguments AA ON 
 AA.Id = I.ApplicationArgument_ID
GROUP BY
 AA.ID,
 AA.WorkStation

C#

var q = from items in db.LogItem

 join aa in db.ApplicationArguments on 
  items.ApplicationArgument.ID equals aa.ID 
 into aaGroup

 from aaJoin in aaGroup.DefaultIfEmpty()

 group items by new 
 {
  aaJoin.ID,
  aaJoin.WorkStation
 } into grouping

 select new 
 {
  Seconds = grouping.Sum(x => SqlFunctions.DateDiff("second", x.DTActivate, x.DTDeActivate)),
  grouping.Key.ID,
  grouping.Key.WorkStation
};

结果SQL非常大(执行计划成本= 0.0199849)

SELECT 
 1 AS [C1], 
 [GroupBy1].[A1] AS [C2], 
 [GroupBy1].[K1] AS [ID], 
 [GroupBy1].[K2] AS [WorkStation] 
FROM 
(
 SELECT 
  [Join1].[K1] AS [K1], 
  [Join1].[K2] AS [K2], 
  SUM([Join1].[A1]) AS [A1] 
  FROM 
  ( 
   SELECT 
    [Extent2].[ID] AS [K1], 
    [Extent2].[WorkStation] AS [K2], 
    DATEDIFF(second, [Extent1].[DTActivate], [Extent1].[DTDeActivate]) AS [A1] 
   FROM 
    [dbo].[DbLogItems] AS [Extent1] 
   LEFT OUTER JOIN [dbo].[DbApplicationArguments] AS [Extent2] 
    ON [Extent1].[ApplicationArgument_ID] = [Extent2].[ID] 
  ) AS [Join1] 
 GROUP BY 
  [K1], 
  [K2] 
) AS [GroupBy1]

帮助请写正确的linq代码 我的SQL执行计划成本= 0.0127553 Linq SQL执行计划成本= 0.0199849 DIFF = 0,0072296 21 + 10条记录

1 个答案:

答案 0 :(得分:1)

LINQ to SQL查询就是这样。有时你不能发出更好的SQL。但是,您可以编写普通的旧T-SQL并以多种方式调用它:一个表值UDF,可能是您自定义的DataContext公开为IQueryable