zoukankan      html  css  js  c++  java
  • Entity Framework

    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);
    复制代码
     
  • 相关阅读:
    安装 oracle
    svn 编辑
    软件构架
    liunx操作
    css的样式分类
    简单自己做了一个个人简历
    网页制作之表格,列表
    MYSQL表创建
    linux操作指令 第二部分
    linux操作指令 第一部分
  • 原文地址:https://www.cnblogs.com/wfy680/p/12380793.html
Copyright © 2011-2022 走看看