[英]Linq-to-SQL: foreign key not accessible until transaction is committed
我发现使用 Linq-to-SQL,当您创建一个新的 object 时,您无法访问外键成员,直到您在上下文中调用SubmitChanges
,新的 object 正在“创建”。 当然,我知道在您将新的 object 提交到数据库之前,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
才能根据已在 object 上设置的原始 ID (FK) 查找值?
是的, c.Teacher
将是 null 那里。 Linq-To-Sql 不提供任何机制来加载基于手动填充的外键列的实体(至少在您到达SubmitChanges
之前不会)。 如果您从数据库中提取实体,它肯定会延迟加载——但在这里您正在创建它。 要么传入teacher
实体(而不是 id),要么手动获取实体并设置它:
c.Teacher = teacher
代替
c.TeacherID = teacherID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.