title: Entity Framework: Counting the number of elements in Collection<T> (performance)
body: <p>I have a collection property in my code-first model:</p>
  
  <pre><code>public class Advertisment
  {
  //...
    public  ICollection&lt;Comment&gt; Comments {get; set;}
  }
  </code></pre>
  
  <p>where Comment is other model-class represents the comment of the  advertisment.
  My task is obvious. The program have to count the number of comments.
  There are two way:</p>
  
  <ol>
  <li><p>through additional Int32-field:</p>
  
  <pre><code>public ICollection&lt;Comment&gt; Comments {get; set; }
  public int NumberOfComments;
  public void IncrementComments() // call after client leave a comment
  {
  NumberOfComments++;
  } 
  public int SumComments() //so, just return the field
  {
  return NumberOfComments;
  }
  </code></pre></li>
  <li><p>through calling the Count method</p>
  
  <pre><code>public int SumComments()
  {
  return db.Comments.Where(c =&gt; c.Advertisment == this).Count(); //where db is instance of DbContext
  }
  </code></pre>
  
  <p>My question about performance. The second way can appear more easy for developing, however, in this case, Entity Framework does make some request for counting elements in DB. Does it have a negative impact on performance?           </p></li>
  </ol>