我正在使用實體框架中的父表和子表。父表是Invoices,子表是InvoiceLineItems。發票表中的每一行自然代表一張發票。並且,InvoiceLineItems表中的每一行代表發票的一行詳細信息(即項目信息,例如項目名稱,價格等)。 InvoiceLineItem表具有發票表的外鍵,因此每個發票對象上都有一個InvoiceLineItems集合。如何在實體框架中分離對象之前加載關聯
一切正常,但我有一個問題。在我們的代碼中,我們建立了處於分離狀態的發票對象列表。然後,我們使用EF數據上下文將所有對象插入到數據庫中(現在它們已附加到會話中)。然後,我們試圖從此會話中分離發票對象,以便我們可以使用新的EF上下文將發票插入另一個數據庫。當我們分離發票時,所有的InvoiceLineItem集合都是空的。是否有辦法在第一次會話關閉之前分離發票並強制裝入行李,以便它們可用於第二個數據上下文?下面的代碼示例演示了我們試圖完成的任務。
// Get a list of invoices from Quickbooks
List<Invoice> qbInvoices = GetInvoicesFromQuickbooks(currentThread);
SaveInvoicesToLocalDatabase(dbContextLocal, qbInvoices, currentThread);
// Detach the Invoices from above context so that we can insert them into
// the second database using the new context below.
// NOTE: All Invoice.InvoiceLineItem collections are empty
// How do we force InvoiceLineItems to load???
qbInvoices = dbContextLocal.Invoices.AsNoTracking().ToList();
dbContextLocal.Dispose();
// This only saves rows to Invoices table (i.e. no InvoiceLineItems are saved)
SaveInvoicesToRemoteDatabase(dbContextWeb, qbInvoices, currentThread);
dbContextWeb.Dispose();