Entity Framework: read one collection and include another?

I have an EF model with ChatRoom, ChatMessage and Member. At some point, I need to get a specific ChatRoom, including all its members, but only with the count of the number of posts in it. In my code below Room-property its members are missing:

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 this, it works:

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

Why Selectis the include statement lost when included in a new anonymous type?

+3
source share
1 answer

Try to include participants in the choice:

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
source

Source: https://habr.com/ru/post/1774767/


All Articles