Entity Framework - Func引起的数据库全表查询

使用 Entity Framework 最要小心的性能杀手就是 —— 不正确的查询代码造成的数据库全表查询。

我们就遇到了一次,请看下面的示例代码:

//错误的代码
Func<QuestionFeed, bool> predicate = null;
if (type == 1)
{
predicate = f => f.FeedID == id && f.IsActive == true;
}
else
{
predicate = f => f.FeedID == id;
}
//_questionFeedRepository.Entities的类型为IQueryable<QuestionFeed>
_questionFeedRepository.Entities.Where(predicate);

上面代码逻辑是根据条件动态生成LINQ查询条件,将Func类型的变量作为参数传给Where方法。

实际上Where要求的参数类型是:Expression<Func<TSource, bool>>。

写代码时没注意这个问题,运行结果也正确。发布后,在SQL Server Profiler监测中,发现QuestionFeed对应的数据库表出现了全表查询,才知道这个地方的问题。

问题就是:

将Func类型的变量作为参数传给Where方法进行LINQ查询时,Enitity Framework会产生全表查询,将整个数据库表中的数据加载到内存,然后在内存中根据Where中的条件进一步查询。

解决方法:

不要用Func<TSource, bool>,用Expression<Func<TSource, bool>>。

//正确的代码
Expression<Func<QuestionFeed, bool>> predicate=null;
if (type == 1)
{
predicate = f => f.FeedID == id && f.IsActive == true;
}
else
{
predicate = f => f.FeedID == id;
}
_questionFeedRepository.Entities.Where(predicate);
posted @ 2012-04-01 14:00  dudu  阅读(9756)  评论(19编辑  收藏  举报