簡體   English   中英

Linq-to-SQL:在提交事務之前無法訪問外鍵

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM