实体导航中的空引用异常

时间:2010-08-23 11:32:10

标签: entity-framework

我有以下EF结构:

alt text

我想获得参加会议的每个用户的名字:

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

我在NullReferenceException行中收到meetingUser.User.Name因为meetingUser.User实例为空。我无法将任何.Include()添加到Meeting,因为两者之间没有任何关系。有没有办法加载它而不在foreach中执行meetingUser.UserReference.Load()

1 个答案:

答案 0 :(得分:0)

一种方式是投射:

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