主要问题是当我在SQL Management studio中执行某个查询时,大约需要2秒钟。当通过实体框架执行并且我使用分析器查看它时,查询需要260秒。结果只有72行1整数。此查询是根据用户定义的过滤器构建的。
有没有人有任何建议可能有什么问题? 我在分析器中可以看到的sqlquery如下:
SELECT [Distinct1].[PersonID] AS [PersonID]
FROM (SELECT DISTINCT [Extent1].[PersonID] AS [PersonID]
FROM (SELECT [PersonViewWithExtraInfo].[PersonID] AS [PersonID],
[PersonViewWithExtraInfo].[DateTime] AS [DateTime],
[PersonViewWithExtraInfo].[ExtraInfo1] AS [ExtraInfo1],
[PersonViewWithExtraInfo].[ExtraInfo2] AS [ExtraInfo2],
[PersonViewWithExtraInfo].[ExtraInfo3] AS [ExtraInfo3],
[PersonViewWithExtraInfo].[ExtraInfo4] AS [ExtraInfo4]
FROM [core].[PersonViewWithExtraInfo].AS [PersonViewWithExtraInfo].AS [Extent1]
LEFT OUTER JOIN [core].[Persons] AS [Extent2]
ON [Extent1].[PersonID] = [Extent2].[PersonID]
WHERE ([Extent1].[ExtraInfo4] = 1)
AND(([Extent2].[FirstName] = 'Steven' /* @p__linq__0 */)
OR (([Extent2].[FirstName] IS NULL)
AND ('Steven' /* @p__linq__0 */ IS NULL))
OR ([Extent2].[FirstName] = 'Steffi' /* @p__linq__1 */)
OR (([Extent2].[FirstName] IS NULL)
AND ('Steffi' /* @p__linq__1 */ IS NULL))
OR ([Extent2].[FirstName] = 'Evy' /* @p__linq__2 */)
OR (([Extent2].[FirstName] IS NULL)
AND ('Evy' /* @p__linq__2 */ IS NULL)))
AND ([Extent1].[DateTime] >= '2014-06-01T00:00:00' /* @p__linq__3 */)
AND ([Extent1].[DateTime] <= '2015-05-31T00:00:00' /* @p__linq__4 */)) AS [Distinct1]
我构建了我的where子句来比较像这样的字符串:
public static Expression<Func<string, bool>> ConvertToExpression(this FilterComparer comparer, string compareValue)
{
switch (comparer)
{
case FilterComparer.IsEqualTo:
return x => x == compareValue;
...
编辑:我发现了问题所在。当我从sqlprofiler中获取查询时,查询被exec sp_executesql包围,当我在管理工作室中粘贴时,查询与EF一样长。因此,当我在此查询中删除空检查时,延迟消失了。当他说“每个where子句有太多表达式”时,我应该听EF编辑器。唯一的问题是实体框架添加了空检查。我该如何防止这种情况?
编辑:这是我从Linq Insight获得的linq查询。
(from x in ((ObjectQuery<PersonViewWithExtraInfo>)PersonViewWithExtraInfo).MergeAs(0)
where x.ExtraInfo4 && (((False || (True && (x.Person.FirstName == compareValue))) || (True && (x.Person.FirstName == compareValue))) || (True && (x.Person.FirstName == compareValue)))
where (x.DateTime >= startDate.Date) && (x.DateTime <= endDate.Date)
select x.PersonID).Distinct()
真实和假的存在是因为查询是根据用户定义的过滤器动态构建的。
答案 0 :(得分:2)
所以问题是EF在查询中添加了空检查,这使得where子句变大了。 通过设置
Configuration.UseDatabaseNullSemantics = true;
在DbContext上问题解决了!