Linq查询从代码缓慢执行而不是从工作室执行

时间:2015-12-05 16:39:52

标签: c# entity-framework sql-server-2008

我有一个Linq-to-Entities查询:

var result = (from sls in context.tbl_sales
              where sls.saleDate == d
              join clnt in context.tbl_clients on sls.clientId equals clnt.clientId
              group sls.quantity by clnt.distributorId into grp
              select new 
                        { distributorId = grp.Key, 
                          Quantity = grp.Sum(e => e) })
             .ToDictionary(e => e.distributorId, e => e.Quantity);

EF生成此SQL查询:

set @p__linq__0='01.11.2015 0:00:00'

SELECT 
    1 AS [C1], 
    [GroupBy1].[K1] AS [distributorId], 
    [GroupBy1].[A1] AS [C2]
    FROM ( SELECT 
        [Extent2].[distributorId] AS [K1], 
        SUM([Extent1].[quantity]) AS [A1]
        FROM  [sales].[tbl_sales] AS [Extent1]
        INNER JOIN [sales].[tbl_clients] AS [Extent2] ON [Extent1].[clientId] = [Extent2].[clientId]
        WHERE [Extent1].[saleDate] = @p__linq__0
        GROUP BY [Extent2].[distributorId]
    )  AS [GroupBy1]

此查询从代码执行,大约需要3-10分钟才能完成。

如果我复制查询并从SQL Server Management Studio运行它,则需要约1秒钟。

为什么代码这么慢?

更新

sql profiler跟踪结果:

exec sp_executesql N'SELECT 
1 AS [C1], 
[GroupBy1].[K1] AS [distributorId], 
[GroupBy1].[A1] AS [C2]
FROM ( SELECT 
    [Extent2].[distributorId] AS [K1], 
    SUM([Extent1].[quantity]) AS [A1]
    FROM  [sales].[tbl_sales] AS [Extent1]
    INNER JOIN [sales].[tbl_clients] AS [Extent2] ON [Extent1].[clientId] =    [Extent2].[clientId]
    WHERE [Extent1].[saleDate] = @p__linq__0
    GROUP BY [Extent2].[distributorId]
    )  AS [GroupBy1]',N'@p__linq__0 datetime2(7)',@p__linq__0='2015-10-01    00:00:00'

UPDATE2: 如果实体框架生成exec sp_executesql索引by saleDate列不工作?

0 个答案:

没有答案