我有以下EF结构:
我想获得参加会议的每个用户的名字:
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()
?
答案 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
}
}