实体框架中的查询比直接sql需要更长的时间
本文关键字:sql 时间 框架 查询 实体 | 更新日期: 2023-09-27 17:55:06
主要问题是,当我在SQL管理工作室执行某个查询需要大约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一样长。因此,当我在这个查询中删除空检查时,延迟就消失了。我应该听EF分析器说的"每个where子句有太多的表达式"。唯一的事情是空检查是由实体框架添加的。我怎样才能避免呢?编辑:这是我从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()
所以问题是EF在查询中添加了null检查,这使得where子句变得很大。通过设置
Configuration.UseDatabaseNullSemantics = true;
在DbContext上,问题解决了!