gro*_*ava 8 c# sql-server entity-framework sql-server-2008 entity-framework-5
主要问题 是否有一些已知的限制,snafu,配置问题,任何事情,这可以解释所有事情都相同的事实,从C#linq运行的查询可能比完成任何其他方式运行要长一个数量级?
这是linq中的缩写查询.它是视图和表之间非常直接的连接.
var query = (
from content in context.ApprovedContentView
where content.BucketId == 13098 && content.ContentTypeId == 5220
join item in context.ActiveContent
on content.ContentId equals item.ItemId
where
item.IsSuchAndSuch == true && item.SomeOtherProperty == 5000
select new
{
ItemId = item.ItemId,
Title = item.Title,
SubTitle = item.SubTitle,
DescriptionText = item.DescriptionText,
/* about 10 other scalar fields */
});
int count = query.Count();
var data = query.OrderByDescending(item => item.ItemId).Skip(5).Take(3);
Run Code Online (Sandbox Code Playgroud)
这是它生成的(缩写/格式化)SQL
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [SchemaX].[ApprovedContentView] AS [Extent1]
INNER JOIN [SchemaX].[ActiveContent] AS [Extent2] ON [Extent1].[ContentId] = [Extent2].[ItemId]
WHERE (13098 = [Extent1].[BucketId]) AND (5220 = [Extent1].[ContentTypeId ]) AND
(1 = [Extent2].[IsSuchAndSuch]) AND (5000 = [Extent2].[SomeOtherProperty ])
) AS [GroupBy1]
GO
SELECT TOP (3)
[Filter1].[BucketId] AS [BucketId],
[Filter1].[ItemId] AS [ItemId],
[Filter1].[Title] AS [Title],
[Filter1].[SubTitle] AS [SubTitle],
[Filter1].[DescriptionText] AS [DescriptionText],
/* other fields */
FROM ( SELECT
[Extent1].[BucketId] AS [BucketId],
[Extent2].[ItemId] AS [ItemId],
[Extent2].[Title] AS [Title],
[Extent2].[SubTitle] AS [SubTitle],
[Extent2].[DescriptionText] AS [DescriptionText],
/* other fields */
row_number() OVER (ORDER BY [Extent2].[DealId] DESC) AS [row_number]
FROM [SchemaX].[ApprovedContentView] AS [Extent1]
INNER JOIN [SchemaX].[ActiveContent] AS [Extent2] ON [Extent1].[ContentId] = [Extent2].[ItemId]
WHERE (13098 = [Extent1].[BucketId]) AND (5220 = [Extent1].[ContentTypeId ]) AND
(1 = [Extent2].[IsSuchAndSuch]) AND (5000 = [Extent2].[SomeOtherProperty ])
) AS [Filter1]
WHERE [Filter1].[row_number] > 5
ORDER BY [Filter1].[DealId] DESC
Run Code Online (Sandbox Code Playgroud)
不同的场景我基于我的速度测试来观察使用sql profiler运行的查询
IN SITU 当这个linq查询在我的c#应用程序中作为其正常操作的一部分执行时,我观察到在sql profiler中,选择计数需要整整3秒才能完成,奇怪的是,产生投影的查询只需要200 ms,并且时间是可重复的,这似乎排除了查询执行计划缓存问题.(与实体框架5一起运行,sql server 2008 r2)
在LINQPAD中, 当我通过LinqPad执行linq语句时,使用C#应用程序的dll数据上下文,计数和投影均在不到四分之一秒内完成(~244ms,总运行时间约为450ms).
在SSMS中, 无论sql的来源如何,当我复制sql profile报告它执行的实际代码并将其粘贴到管理工作室窗口并执行时,大约需要224ms.
数据库调优 在SSMS中,当我评估我从探查器(从代码或从linqpad复制)复制的sql的实际执行计划时,我发现sql正在使用所有正确的索引,并且仅报告索引搜索 - 没有表扫描,没有摆脱查找.
那么,是什么给出的?有人见过这样的事吗?
我会确保您没有为您的应用程序缓存的错误执行计划.在对已经使用的数据库进行模式处理时,这经常发生在我身上.您可能有一个已针对应用程序执行上下文缓存的执行计划,该计划由于架构更改而效率低下,而为SSMS查询生成的执行计划是最新的,并且没有看到这些性能问题.
我会尝试使用DBCC FREEPROCCACHE强制更新您的执行计划,看看是否能解决问题.