3

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 with 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?

Ani
  • 111,048
  • 26
  • 262
  • 307
Andreas Zita
  • 7,232
  • 6
  • 54
  • 115

1 Answers1

0

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);
as-cii
  • 12,819
  • 4
  • 41
  • 43