开发者

Entity Framework: Count one collection and Include another?

I have a EF-model with ChatRoom, ChatMessage and Participant. At one point I need to fetch a certain ChatRoom including all its participants but only wit开发者_如何学运维h a count of the number of messages in it. In my code below, the Room-property is missing its participants:

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?


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜