views:

18

answers:

1

I have the following EF structure:

alt text

I want to get name of the every user who attended to a meeting:

using(var ctx = new MyContext())
{
    var meeting = (from row in ctx.Meetings.Include("MeetingMessages").Include("MeetingUsers")
            where row.mId == 1
            select row).FirstOrDefault();

    foreach(var meetingUser in meeting.MeetingUsers)
    {
        MessageBox.Show(meetingUser.User.Name); //<== exception
    }
}

I'm getting NullReferenceException in meetingUser.User.Name line because meetingUser.User instance is null. I can't add any .Include() to Meeting because there are no relations in between. Is there a way to load it without doing meetingUser.UserReference.Load() in foreach?

A: 

One way is to project:

using(var ctx = new MyContext())
{
    var meeting = (from row in ctx.Meetings
                   where row.mId == 1
                   select new
                   {
                       Meeting = row,
                       MeetingUsers = row.MeetingUsers,
                       Users = from u in row.MeetingUsers
                               select u.User
                   }).First();

    foreach(var meetingUser in meeting.MeetingUsers)
    {
        MessageBox.Show(meetingUser.User.Name); //<== exception
    }
}
Craig Stuntz
That was certainly an eye opener. Thank you.
Armagan