【问题标题】:OutOfMemory Exception for Where clauseWhere 子句的 OutOfMemory 异常
【发布时间】:2017-08-07 12:52:28
【问题描述】:

我正在使用带有 LazyLoadEnabled = false 配置的实体框架 6。我在我的项目中使用 UnitOfwork 存储库模式。 我在一个表中有大约 1,50,000 条记录,与大约 5 个表有外键关系。现在我的要求是我必须实现服务器端分页。为此,首先我在应用一些基本过滤器(如 isactive 和由用户创建)后查询此表以获取准确计数,如下所示:

public long Count(Func<TEntity,bool> where)
{
    return DbSet.Where(where).Count();
}

然后我正在应用一些搜索字符串过滤器并包括一些外部引用,如下所示:

public IQueryable<TEntity> GetWithInclude(Expression<Func<TEntity, bool>> predicate, params string[] include)
{
    IQueryable<TEntity> query = this.DbSet;
    query = include.Aggregate(query, (current, inc) => current.Include(inc));
    return query.Where(predicate);
}

但是在这两种方法中,我都得到了OutOfMemory exception,因为我使用了Where 子句。请帮我解决这个问题。

【问题讨论】:

    标签: c# sql entity-framework out-of-memory


    【解决方案1】:

    也许您应该更改签名以包含 Expression 以避免将记录全部加载到内存中。

    public long Count(Expression<Func<TEntity,bool>> where)
    

    旁白: LINQ 已经有一个Count 运算符可供您使用。

    【讨论】:

      【解决方案2】:

      这实际上只是为了扩展answer from Daniel。因为您的Count 方法采用Func&lt;TEntity,bool&gt;,所以您强制编译器选择Enumerable.Where 而不是更具体的Queryable.Where。这会强制将您的整个 DbSet 物化到内存中 - 所有 1,500,000 行。所以将方法签名改为使用Expression,当你在那里时,你不需要调用Where,而是使用Count的另一个重载:

      public long Count(Expression<Func<TEntity,bool>> where)
      {
          return DbSet.Count(where);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        • 2018-06-18
        • 2015-04-25
        • 2016-04-26
        • 2014-07-15
        相关资源
        最近更新 更多