Reputation: 21186
I have read a few other posts here but i'm not sure I'm quite satisified yet...
Take the following:
class Whatever
{
/// <summary>
/// Messages can relate to messages through replies
/// </summary>
public virtual IList<FieldMessage> FieldMessages { get; set; }
[NotMapped]
public int UnreadMessageCount
{
get
{
if( this.FieldMessages == null )
{
return 0;
}
return this.FieldMessages.Where(x => x.Read == false).Count();
}
}
}
This is an entity framework class...
My questions:
virtual IList properties
or does it way for you to call it before doing that?UnreadMessageCount
... I noticed that on the if statement, this.FieldMessages
takes the entire 6300 entires which I can look at while debugging, and then does the .Where
statement at gets the count... Is it really doing that? Or is it just because i'm debugging it?Upvotes: 2
Views: 1422
Reputation: 13138
A query is made as soon as you try to use the collection : call to Count
property, iteration using an IEnumerable
extension method or foreach
, ...). The whole collection will be loaded at first use then the collection stays in the context.
When you try read values in the debugger, methods of the collection are called and the database is queried.
If FieldMessages
contains 6300 entries then maybe you should avoid declaring the collection on Whatever
class. Use the context and FieldMessage
's DbSet
to query unread messages attached to a specific Whatever
instance with unread state.
Upvotes: 1