I have a data call in a Linq to Entities powered data access layer that is designed to make paged calls.
In doing so, I need to select a subset of the data, say 50 rows, but also get the count of all matches to know how many total matches exist to be paged through.
Currently, I'm doing the following:
var queryResult = DatabaseContext.Table
.Where(x => !x.IsDeleted)
.Where(p => (
p.PropertyOne.ToLower().Contains(query) ||
p.PropertyTwo.ToLower().Contains(query)
));
int count = queryResult.Count();
var returnData = queryResult
.OrderBy(i => i.ID)
.Skip(start).Take((length))
.Select(y => new ObjectDTO
{
PropertyOne = y.PropertyOne,
PropertyTwo = y.PropertyTwo
}
.AsEnumerable();
This results in two costly database operations. The COUNT
operation for some reason actually takes longer than the SELECT
operation.
Is there a way to get count and a subset in the same operation?
The logical flow to me says we do the following:
- Look at Table
- Find Items in Table that match a condition
- Get a Count of all matches
- Return a numbered subset of the matches
This seems possible in one operation, but I cannot figure out how.
Attempt One, Slower
Tried D Stanley's suggestion of casting the full result set to a List
and doing count and memory in paging, but it is roughly 2x slower (6.9s avg vs 3.9s avg)
It's worth mentioning the data set is roughly 25,000 records, with over a dozen related tables that are searched in a JOIN.
queryResult
to aList<T>
and use.Count
on the list, is it faster? – Quadraticsstart
+length
matches. – Rodriguezcount
in the code. I meanint count = queryResult.Count();
– Electromotive