HOW TO:使用消極式載入來載入相關物件 (Entity Framework)
本主題顯示如何使用消極式載入來載入相關物件。 啟用消極式載入後,在透過導覽屬性存取相關物件時,便會載入這些物件。 您仍可以使用 Include 方法積極載入物件,或使用 LoadProperty 方法明確載入它們。 如需詳細資訊,請參閱載入相關的物件 (Entity Framework)。
在 Entity Framework 執行階段中,ObjectContext 執行個體中之 LazyLoadingEnabled 屬性的預設值是 false。 不過,如果您使用 Entity Framework 工具建立新的模型和對應的產生類別,產生的程式碼會在產生之物件內容的建構函式中,將 LazyLoadingEnabled 設定為 true。
本主題的範例根據 Adventure Works Sales Model。若要執行此主題中的程式碼,您必須已經將 Adventure Works Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework) 或 HOW TO:手動設定 Entity Framework 專案及 HOW TO:手動設定 Entity Framework 專案。
範例
下列範例顯示十個連絡人且讓使用者選取一個連絡人。 根據選取的連絡人再載入相關的訂單。
Class LazyLoading
Public Sub EnableLazyLoading()
Using context As New AdventureWorksEntities()
' You do not have to set context.ContextOptions.LazyLoadingEnabled to true
' if you used the Entity Framework to generate the object layer.
' The generated object context type sets lazy loading to true
' in the constructor.
context.ContextOptions.LazyLoadingEnabled = True
' Display ten contacts and select a contact
Dim contacts = context.Contacts.Take(10)
For Each c In contacts
Console.WriteLine(c.ContactID)
Next
Console.WriteLine("Select a customer:")
Dim contactID As Int32 = Convert.ToInt32(Console.ReadLine())
' Get a specified customer by contact ID.
Dim contact = context.Contacts.Where(Function(c) c.ContactID = contactID).FirstOrDefault()
' If lazy loading was not enabled no SalesOrderHeaders would be loaded for the contact.
For Each order As SalesOrderHeader In contact.SalesOrderHeaders
Console.WriteLine("SalesOrderID: {0} Order Date: {1} ", order.SalesOrderID, order.OrderDate)
Next
End Using
End Sub
End Class
class LazyLoading
{
public void EnableLazyLoading()
{
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// You do not have to set context.ContextOptions.LazyLoadingEnabled to true
// if you used the Entity Framework to generate the object layer.
// The generated object context type sets lazy loading to true
// in the constructor.
context.ContextOptions.LazyLoadingEnabled = true;
// Display ten contacts and select a contact
var contacts = context.Contacts.Take(10);
foreach (var c in contacts)
Console.WriteLine(c.ContactID);
Console.WriteLine("Select a customer:");
Int32 contactID = Convert.ToInt32(Console.ReadLine());
// Get a specified customer by contact ID.
var contact = context.Contacts.Where(c => c.ContactID == contactID).FirstOrDefault();
// If lazy loading was not enabled no SalesOrderHeaders would be loaded for the contact.
foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
{
Console.WriteLine("SalesOrderID: {0} Order Date: {1} ",
order.SalesOrderID, order.OrderDate);
}
}
}
}
另請參閱
工作
HOW TO:使用查詢路徑來設定結果外觀 (Entity Framework)
HOW TO:明確載入相關的物件 (Entity Framework)