c# - Entity Framework COUNT is doing a SELECT of all records -
profiling code because taking long time execute, generating select instead of count , there 20,000 records very slow.
this code:
var catviewmodel= new catviewmodel(); var catcontext = new catentities(); var cataccount = catcontext.account.single(c => c.accountid == accountid); catviewmodel.numberofcats = cataccount.cats.count();
it straightforward stuff, code profiler showing is:
exec sp_executesql n'select [extent1].xxxxx yyyyy, [extent1].xxxxx yyyyy, [extent1].xxxxx yyyyy, [extent1].xxxxx yyyyy // idea [dbo].[cats] [extent1] cats.[accountid] = @entitykeyvalue1',n'@entitykeyvalue1 int',@entitykeyvalue1=7
i've never seen behaviour before, ideas?
edit: fixed if instead:
catviewmodel.numberofrecords = catcontext.cats.where(c => c.accountid == accountid).count();
i'd still know why former didn't work though.
so have 2 separate queries going on here , think can explain why different results. let's @ first one
// pull single account record var cataccount = catcontext.account.single(c => c.accountid == accountid); // count associated cat records against said account catviewmodel.numberofcats = cataccount.cats.count();
going on assumption cats
has 0..*
relationship account
, assuming leveraging frameworks ability lazily load foreign tables first call cataccounts.cats
going result in select
associated cat
records particular account. results in table being brought memory therefore call count()
result in internal check of count
property of in-memory collection (hence no count
sql generated).
the second query
catviewmodel.numberofrecords = catcontext.cats.where(c => c.accountid == accountid).count();
is directly against cats
table (which iqueryable<t>
) therefore operations performed against table where
/count
, , both of these evaluated on db-side before execution it's lot more efficient first.
however, if need both account
, cats
recommend eager load data on fetch, way take hit upfront once
var cataccount = catcontext.account.include(a => a.cats).single(...);
Comments
Post a Comment