Jimmyt1988
Jimmyt1988

Reputation: 21186

When does entity framework actually make the call to the database

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:

  1. Does Entity framework lazy load those virtual IList properties or does it way for you to call it before doing that?
  2. When you're in your view, and you're doing a loop over the list of Whatever objects... and each loop you call the 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?
  3. Do you have a good article about when on earth Entity Framework actually makes the database calls... I need to avoid memory being filled up because this site is to be used by thousands making messages all the time.

Upvotes: 2

Views: 1422

Answers (1)

Guillaume
Guillaume

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

Related Questions