title: How To Count Associated Entities Without Fetching Them In Entity Framework
body: <p>I've been wondering about this one for a while now, so I thought it would be worth using my first Stack Overflow post to ask about it.</p>
  
  <p>Imagine I have a discussion with an associated list of messages:</p>
  
  <pre><code>DiscussionCategory discussionCategory = _repository.GetDiscussionCategory(id);
  </code></pre>
  
  <p>discussionCategory.Discussions is a list of Discussion entities which is not currently loaded.</p>
  
  <p>What I want is to be able to iterate through the discussions in a discussionCategory and say how many messages are in each discussion without fetching the message data.</p>
  
  <p>When I have tried this before I have had to load the Discussions and the Messages so that I could do something like this:</p>
  
  <pre><code>discussionCategory.Discussions.Attach(Model.Discussions.CreateSourceQuery().Include("Messages").AsEnumerable());
  
  foreach(Discussion discussion in discussionCategory.Discussions)
  {
  
  int messageCount = discussion.Messages.Count;
  
  Console.WriteLine(messageCount);
  
  }
  </code></pre>
  
  <p>This seems rather inefficient to me as I am fetching potentially hundreds of message bodies from the database and holding them in memory when all I wish to do is count their number for presentational purposes.</p>
  
  <p>I have seen some questions which touch on this subject but they did not seem to address it directly.</p>
  
  <p>Thanks in advance for any thoughts you may have on this subject.</p>
  
  <p>Update - Some more code as requested:</p>
  
  <pre><code>public ActionResult Details(int id)
      {  
          Project project = _repository.GetProject(id);
          return View(project);
      }
  </code></pre>
  
  <p>Then in the view (just to test it out):</p>
  
  <pre><code>Model.Discussions.Load();
  var items = from d in Model.Discussions select new { Id = d.Id, Name = d.Name, MessageCount = d.Messages.Count() };
  
  foreach (var item in items) {
  //etc
  </code></pre>
  
  <p>I hope that makes my problem a bit clearer. Let me know if you need any more code details.</p>