How To Count Associated Entities Without Fetching Them In Entity Framework

后端 未结 6 1616
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  名媛妹妹
    2021-01-30 21:24

    Easy; just project onto a POCO (or anonymous) type:

    var q = from d in Model.Discussions
            select new DiscussionPresentation
            {
                Subject = d.Subject,
                MessageCount = d.Messages.Count(),
            };
    

    When you look at the generated SQL, you'll see that the Count() is done by the DB server.

    Note that this works in both EF 1 and EF 4.

提交回复
热议问题