Where 子句的 OutOfMemory 异常
OutOfMemory Exception for Where clause
我正在使用 entity Framework 6 和 LazyLoadEnabled = false
配置什么都没有 else.I 在我的项目中使用 UnitOfwork 存储库模式。
我在 table 中有大约 1,50,000 条记录,外键关系约为 5 tables。现在我的要求是我必须实现服务器端 pagination.For ,首先我查询这个 table 以在应用一些基本过滤器(如 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
子句。请帮我解决这个问题。
也许您应该更改您的签名以包含 Expression
以避免将记录全部加载到内存中。
public long Count(Expression<Func<TEntity,bool>> where)
旁白: LINQ 已经有一个可以使用的 Count
运算符。
这真的只是为了扩展. Because your Count
method takes a Func<TEntity,bool>
, you are forcing the compiler to choose Enumerable.Where
instead of the more specific Queryable.Where
。这会强制将整个 DbSet 实体化到内存中——所有 1,500,000 行。因此,将方法签名改为采用 Expression
,当你在那里时,你不需要调用 Where
,而是使用 Count
的另一个重载:
public long Count(Expression<Func<TEntity,bool>> where)
{
return DbSet.Count(where);
}
我正在使用 entity Framework 6 和 LazyLoadEnabled = false
配置什么都没有 else.I 在我的项目中使用 UnitOfwork 存储库模式。
我在 table 中有大约 1,50,000 条记录,外键关系约为 5 tables。现在我的要求是我必须实现服务器端 pagination.For ,首先我查询这个 table 以在应用一些基本过滤器(如 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
子句。请帮我解决这个问题。
也许您应该更改您的签名以包含 Expression
以避免将记录全部加载到内存中。
public long Count(Expression<Func<TEntity,bool>> where)
旁白: LINQ 已经有一个可以使用的 Count
运算符。
这真的只是为了扩展Count
method takes a Func<TEntity,bool>
, you are forcing the compiler to choose Enumerable.Where
instead of the more specific Queryable.Where
。这会强制将整个 DbSet 实体化到内存中——所有 1,500,000 行。因此,将方法签名改为采用 Expression
,当你在那里时,你不需要调用 Where
,而是使用 Count
的另一个重载:
public long Count(Expression<Func<TEntity,bool>> where)
{
return DbSet.Count(where);
}