简体   繁体   English

Linq-to-SQL:在提交事务之前无法访问外键

[英]Linq-to-SQL: foreign key not accessible until transaction is committed

I've found that with Linq-to-SQL, when you create a new object you can not access a foreign-key member until you have called SubmitChanges on the context the new object is being "created with."我发现使用 Linq-to-SQL,当您创建一个新的 object 时,您无法访问外键成员,直到您在上下文中调用SubmitChanges ,新的 object 正在“创建”。 I understand, of course, that the FK doesn't really exist until you've committed the new object to the database - but it seems that the information is there to allow the lookup to work.当然,我知道在您将新的 object 提交到数据库之前,FK 并不真正存在 - 但似乎该信息允许查找工作。 Take, for example, the code below.以下面的代码为例。

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

The above code has some comments that should illustrate what I'm asking.上面的代码有一些注释应该说明我在问什么。 My question is basically this:我的问题基本上是这样的:

Why must I first SubmitChanges in order to lookup a value based on a primitive ID (FK) which is already set on the object?为什么我必须首先SubmitChanges才能根据已在 object 上设置的原始 ID (FK) 查找值?

Yes, c.Teacher would be null there.是的, c.Teacher是 null 那里。 Linq-To-Sql does not provide any mechanism to load an entity based on a manually populated foreign-key column (at least, not until you get to SubmitChanges ). Linq-To-Sql 不提供任何机制来加载基于手动填充的外键列的实体(至少在您到达SubmitChanges之前不会)。 Certainly it would lazy-load if you had pulled the entity from the db -- but here you are creating it.如果您从数据库中提取实体,它肯定会延迟加载——但在这里您正在创建它。 Either pass in the teacher entity (instead of the id) or manually fetch the entity and set that instead:要么传入teacher实体(而不是 id),要么手动获取实体并设置它:

c.Teacher = teacher

Instead of代替

c.TeacherID = teacherID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM