I'd like to write a function, that retrieves data from a database table page by page. The goal here is to save memory. This is a part of a validation program that we will be running on our database occasionally to make sure that we have consistent data. Tables could be quite big, so I would not want to load the whole table to memory for doing the validation.
With that in mind I wrote this function:
static IEnumerable<T> RetreivePages<T>(IQueryable<T> query, int count, int pageSize)
{
int pages = count / pageSize;
if (count % pageSize > 0)
{
pages++;
}
for (int i = 0; i < pages; i++)
{
foreach (T item in query.Skip(i * pageSize).Take(pageSize))
{
yield return item;
}
}
}
The idea here is that we are only retrieving pageSize
rows at a time, so we won't fill memory with all the rows from a table.
Unfortunately that does not work. query.Skip
line throws the following exception:
The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.
Is there any other way to accomplish what I want?
Update
The answers to the question linked as duplicate suggest ordering by a column. .OrderBy
would not work here because properties on T
are not known inside the function.