I have the following EF structure:
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 meeti开发者_如何学Gong.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?
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
}
}
精彩评论