How To Count Associated Entities Without Fetching Them In Entity Framework

后端 未结 6 1493
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 20:50

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.

Imagine I have a discussion with

6条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 21:12

    If you are using Entity Framework 4.1 or later, you can use:

    var discussion = _repository.GetDiscussionCategory(id);
    
    // Count how many messages the discussion has 
    var messageCount = context.Entry(discussion)
                          .Collection(d => d.Messages)
                          .Query()
                          .Count();
    

    Source: http://msdn.microsoft.com/en-US/data/jj574232

提交回复
热议问题