【发布时间】:2011-06-07 22:46:06
【问题描述】:
我发现使用 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.
}
}
上面的代码有一些 cmets 应该说明我在问什么。我的问题基本上是这样的:
为什么我必须首先 SubmitChanges 才能根据已在对象上设置的原始 ID (FK) 查找值?
【问题讨论】:
标签: c# .net linq-to-sql datacontext