开发者

Null reference exception in entity navigation

I have the following EF structure:

Null reference exception in entity navigation

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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜