简体   繁体   English

实体框架:统计一个集合并包含另一个集合?

[英]Entity Framework: Count one collection and Include another?

I have a EF-model with ChatRoom, ChatMessage and Participant. 我有一个带有ChatRoom,ChatMessage和Participant的EF模型。 At one point I need to fetch a certain ChatRoom including all its participants but only with a count of the number of messages in it. 有一次,我需要获取某个ChatRoom,包括其所有参与者,但只需要计算其中的消息数。 In my code below, the Room -property is missing its participants: 在我的下面的代码中, Room -property缺少其参与者:

var res = context.Entities
                 .OfType<ChatRoom>()
                 .Include("Participants")
                 .Select(r => new
                              {
                                 Room = r,
                                 Messages = r.ChatMessages.Count()
                              })
                 .FirstOrDefault(c => c.Room.Id == id);

When doing it like this it works: 这样做的时候有效:

var res = context.Entities
                 .OfType<ChatRoom>()
                 .Include("Participants")
                 .FirstOrDefault(r => r.Id == id);

Why is the including-statement lost when doing a Select to a new anonymous type? 为什么在Select新的匿名类型时,包含语句会丢失?

Try to include participants in select: 尝试将参与者包括在选择中:

var res = context.Entities
             .OfType<ChatRoom>()
             .Include("Participants") // I think this could be removed.
             .Select(r => new
                          {
                             Room = r,
                             Messages = r.ChatMessages.Count(),
                             Participants = r.Participants
                          })
             .FirstOrDefault(c => c.Room.Id == id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM