• 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);
  • 相关阅读:
    HDU 2095 find your present (2) (异或)
    UESTC 486 Good Morning (水题+坑!)
    UVa 111 History Grading (简单DP,LIS或LCS)
    UVa 11292 Dragon of Loowater (水题,排序)
    HDU 1503 Advanced Fruits (LCS+DP+递归)
    UVa 10881 Piotr's Ants (等价变换)
    UVa 11178 Morley's Theorem (几何问题)
    HDU 1285 确定比赛名次(拓扑排序)
    .net Core的例子
    TCP与UDP的区别
  • 原文地址:https://www.cnblogs.com/dudu/p/enitity_framework_func.html
Copyright © 2020-2023  润新知