I've a little question about performance with Entity Framework.
Something like
using (MyContext context = new MyContext())
{
Document DocObject = context.Document.Find(_id);
int GroupCount = context.Document.Where(w=>w.Group == DocObject.Group).ToList().Count();
}
takes about 2 seconds in my database (about 30k datasets), while this one
using (MyContext context = new MyContext())
{
Document DocObject = context.Document.Find(_id);
int GroupCount = context.Document.Where(w=>w.Group == DocObject.Group).Count();
}
takes 0,02 seconds.
When my filter for 10 documents had 20 seconds to wait, I checked my code, and changed this to not use ToList()
before Count()
.
Any ideas why it needs 2 seconds for this line with the ToList()
?
Please use the Count() method. IQueryable<People> list = repository. FindAllPeople; int cnt = list. Count();
Calling ToList()
then Count()
will:
SELECT FROM WHERE
against your databaseList<T>
object containing all the resultsCount
property of the .Net list you just createdCalling Count()
against an IQueryable
will:
SELECT COUNT FROM WHERE
against your databaseInt32
with the number of rowsObviously, if you're only interested in the number of items (not the items themselves), then you shouldn't ever call ToList()
first, as it will require a lot of resources for nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With