开发者

Null reference exception in entity navigation

开发者 https://www.devze.com 2023-01-13 04:44 出处:网络
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())

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

精彩评论

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