我发现使用Linq-to-SQL时,在创建新对象时,除非在上下文中调用SubmitChanges
,否则无法访问外键成员“。当然,我理解,在您将新对象提交到数据库之前,FK并不存在 - 但似乎信息是允许查找工作的。以下面的代码为例。
public Course Create(string name, int teacherID)
{
using (MyDataContext context = new MyDataContext())
{
Course c = new Course();
c.Name = name;
c.TeacherID = teacherID; //FK here, assume the value references a valid Teacher.
context.Courses.InsertOnSubmit(c); //c now has a context it can use.
//Try to do some validation here, before commiting the Course to the database.
//c.Teacher will be null here, leading to an exception.
if (c.Teacher.FirstName.Equals("Phil"))
throw new ApplicationException("Phil quit last year."); //Throwing here would cause the transaction to never commit, good.
context.SubmitChanges();
//Email the teacher.
SendEmail(c.Teacher.EmailAddress); //c.Teacher is no longer null, this would work fine.
}
}
上面的代码有一些注释可以说明我的要求。我的问题基本上是这样的:
为什么我必须先SubmitChanges
才能根据已在对象上设置的基本ID(FK)查找值?
答案 0 :(得分:4)
是的,c.Teacher
在那里为空。 Linq-To-Sql没有提供任何基于手动填充的外键列加载实体的机制(至少,直到你到达SubmitChanges
)。当然,如果你从数据库中拉出实体,它会延迟加载 - 但是你在这里创建它。传入teacher
实体(而不是id)或手动获取实体并设置相反:
c.Teacher = teacher
而不是
c.TeacherID = teacherID