Reputation: 27
please see this query
return ContextDb.TestTbl.AsNoTracking().Where(x =>
x.Field1 == newsPaperGroupId).OrderByDescending(x => x.ShowDateTime).Take(count).ToList();
Is it fetch all record then take n record?
Is there any faster way to do this query?
Upvotes: 0
Views: 56
Reputation: 66501
LINQ uses deferred execution, which means that it doesn't retrieve results right away - not until you call certain methods like ToList()
, Single()
, Count()
, or iterate over the query with a foreach
loop, etc.
If your query looked like this, then it'd actually be grabbing all the records where Field1 == newsPaperGroupId
before taking count
into consideration.
return ContextDb.TestTbl.AsNoTracking()
.Where(x => x.Field1 == newsPaperGroupId)
.OrderByDescending(x => x.ShowDateTime)
.ToList()
.Take(count);
And if it looked like this, then it'd be grabbing everything in TestTbl
(ouch) before applying the filter or limiting the number of records taken.
return ContextDb.TestTbl.AsNoTracking()
.ToList()
.Where(x => x.Field1 == newsPaperGroupId)
.OrderByDescending(x => x.ShowDateTime)
.Take(count);
But what you've got looks fine. It doesn't retrieve the actual data until you've applied the filter and limited the number of records to retrieve.
Upvotes: 1