1

I'm having an issue where objects are coming back as null even if they passed linq tests and I can see the values in the db, and I am stuck unsure where to go to fix this. I'm not normally a c# developer so this is new territory for me.

My table looks like

Class Meeting {
...
public virtual List<MeetingParticipant> Participants { get; set; }
...
}

Class MeetingParticipant {
    public bool isOrganiser { get; set; }
    public Account Participant { get; set; }
    public ParticipatingState ParticipatingState { get; set; }
    public string responseText { get; set; }
}

the only bind i have is: modelBuilder.Entity<Meeting>().OwnsMany(meeting => meeting.Participants);

and my linq command is:

var meetings = (from m in _context.Meetings
                     where m.Participants.Any(val => val.Participant.PhoneNumber == passedInPhoneNumber && val.ParticipatingState == ParticipatingState.Pending)
                     select m);

Annoyingly when I dig into the meetup objects that are returned, there is participants however their Account object is null. However, for the meetup to pass the linq request, it had to exist so I could compare its phone number. What am I missing?

Beau
  • 43
  • 7
  • You need to `Include()` related entities. – CodeCaster Nov 26 '20 at 20:27
  • Does this answer your question? [Entity Framework - Include Multiple Levels of Properties](https://stackoverflow.com/questions/10822656/entity-framework-include-multiple-levels-of-properties) – queue Nov 26 '20 at 20:42

1 Answers1

1

A simple adjustment to your Linq command should get you the results you want:

var meetings = from m in _context.Meetings.Include(val => val.Participant)
               where m.Participants.Any(val => val.Participant.PhoneNumber == passedInPhoneNumber && val.ParticipatingState == ParticipatingState.Pending)
               select m;

The .Include(val => val.Participant) is the magic here - it tells EF to "eagerly" load and populate that entity in your results.

Learn more about eager loading here: https://www.entityframeworktutorial.net/eager-loading-in-entity-framework.aspx

Edit: As mentioned in Beau's comment, for this to work, you need to add the following using statement:

using System.Data.Entity; 
RMD
  • 2,907
  • 30
  • 47
  • 1
    I saw this but it didn't work the first time I tried it. Though with your feedback, I dug a bit deeper did I notice I wasn't properly importing certain frameworks from Nuget and the "Include" function wasn't yet in the project. That and your example was exactly what I needed! Thank you for your help! – Beau Nov 26 '20 at 20:58