Reputation: 85
I am using entity Framework 6 with LazyLoadEnabled = false
configuration nothing else.I am using UnitOfwork repository pattern in my project.
And I have around 1,50,000 records in a table with foreign key relations to around 5 tables. Now my requirement is I have to implement server side pagination.For that, first I am querying this table to get exact count after applying some basic filters(like isactive and created by user) like below :
public long Count(Func<TEntity,bool> where)
{
return DbSet.Where(where).Count();
}
then I am applying some search string filter and include some foreign references like below :
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);
}
but in both methods, I am getting OutOfMemory exception
since I have used Where
clause . Kindly help me to get rid of this problem.
Upvotes: 0
Views: 127
Reputation: 118937
This is really just to expand on the answer from Daniel. 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
. This forces your entire DbSet to be materialised into memory - all 1,500,000 rows. So change the method signature to take an Expression
instead, and while you're there, you don't need to call Where
, instead use the other overload of Count
:
public long Count(Expression<Func<TEntity,bool>> where)
{
return DbSet.Count(where);
}
Upvotes: 0
Reputation: 190915
Perhaps you should change your signature to include Expression
to avoid the full load of the records into memory.
public long Count(Expression<Func<TEntity,bool>> where)
Aside: LINQ already has a Count
operator that you can use.
Upvotes: 2