EntityCollection<TEntity>.Load(MergeOption) 方法


使用指定的合併選項,將相關物件載入集合中。Loads related objects into the collection, using the specified merge option.

 override void Load(System::Data::Objects::MergeOption mergeOption);
public override void Load (System.Data.Objects.MergeOption mergeOption);
override this.Load : System.Data.Objects.MergeOption -> unit
Public Overrides Sub Load (mergeOption As MergeOption)



指定這個集合中的物件應該如何與可能已經從針對相同 ObjectContext 的先前查詢所傳回的物件合併。Specifies how the objects in this collection should be merged with the objects that might have been returned from previous queries against the same ObjectContext.


這個範例是以「 艾德作品」銷售模型為基礎。This example is based on the Adventure Works Sales Model. 若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. 若要這樣做,請完成 how to:手動設定 Entity Framework 專案 和 how To:手動定義模型和對應檔中的程式。To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define the Model and Mapping Files.

這個範例會載入 SalesOrderHeader 實體的相關 Contact 物件。This example loads the related SalesOrderHeader objects for the Contact entity.

// Specify the customer ID.
int contactID = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
    context.ContextOptions.LazyLoadingEnabled = false;

    // Get a specified customer by contact ID.
    var contact =
        (from c in context.Contacts
         where c.ContactID == contactID
         select c).First();

    // Load the orders for the customer explicitly.
    if (!contact.SalesOrderHeaders.IsLoaded)

    foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
        // Load the items for the order if not already loaded.
        if (!order.SalesOrderDetails.IsLoaded)

        Console.WriteLine(String.Format("PO Number: {0}",
        Console.WriteLine(String.Format("Order Date: {0}",
        Console.WriteLine("Order items:");
        foreach (SalesOrderDetail item in order.SalesOrderDetails)
            Console.WriteLine(String.Format("Product: {0} "
                + "Quantity: {1}", item.ProductID.ToString(),
' Specify the customer ID. 
Dim contactID As Integer = 4332

Using context As New AdventureWorksEntities()
    context.ContextOptions.LazyLoadingEnabled = False

    ' Get a specified customer by contact ID. 
    Dim contact = (From c In context.Contacts
        Where c.ContactID = contactID
        Select c).First()

    ' Load the orders for the customer explicitly. 
    If Not contact.SalesOrderHeaders.IsLoaded Then
    End If

    For Each order As SalesOrderHeader In contact.SalesOrderHeaders
        ' Load the items for the order if not already loaded. 
        If Not order.SalesOrderDetails.IsLoaded Then
        End If

        Console.WriteLine(String.Format("PO Number: {0}", order.PurchaseOrderNumber))
        Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
        Console.WriteLine("Order items:")
        For Each item As SalesOrderDetail In order.SalesOrderDetails
            Console.WriteLine(String.Format("Product: {0} Quantity: {1}", _
                                              item.ProductID.ToString(), item.OrderQty.ToString()))
End Using


這個方法 RelatedEnd.ValidateLoad 會在載入集合之前呼叫內部方法,這會驗證的呼叫 Load 是否有正確的條件。This method calls the internal RelatedEnd.ValidateLoad method before loading the collection, which validates that a call to Load has the correct conditions. RelatedEnd.ValidateLoad方法會檢查:The RelatedEnd.ValidateLoad method checks that:

當集合中的物件已經載入至時 ObjectContext ,方法會 Load 強制執行 MergeOption 參數所指定的 mergeOptionWhen objects in the collection are already loaded into the ObjectContext, the Load method enforces the MergeOption specified by the mergeOption parameter. 如需詳細資訊,請參閱 識別解析、狀態管理及變更追蹤For more information, see Identity Resolution, State Management, and Change Tracking.

若要明確載入相關物件,您必須 Load 在導覽屬性所傳回的相關端點上呼叫方法。To explicitly load related objects, you must call the Load method on the related end returned by the navigation property. 針對一對多關聯性,請 Load 在上呼叫方法 EntityCollection<TEntity>For a one-to-many relationship, call the Load method on EntityCollection<TEntity>. 如果是一對一關聯性,請 Load 在上呼叫 EntityReference<TEntity>For a one-to-one relationship, call the Load on EntityReference<TEntity>. 這樣就會將相關物件資料載入物件內容中。This loads the related object data into the object context. 您可以使用 Visual Basic) 中的迴圈 (來列舉傳回結果的集合 foreach For Each...Next ,並有條件地針對結果中的 Load EntityReference<TEntity> EntityCollection<TEntity> 每個實體呼叫和屬性的方法。You can enumerate through the collection of returned results using a foreach loop (For Each...Next in Visual Basic) and conditionally call the Load method on EntityReference<TEntity> and EntityCollection<TEntity> properties for each entity in the results.

Load無論是否為,方法都會從資料來源載入相關物件 IsLoaded trueThe Load method loads related objects from the data source whether or not IsLoaded is true.


Load (C#) 或 foreach (Visual Basic) 列舉期間呼叫 For Each 方法時,物件服務會嘗試開啟新的資料讀取器。When you call the Load method during a foreach (C#) or For Each (Visual Basic) enumeration, Object Services tries to open a new data reader. 除非您在連接字串中指定 multipleactiveresultsets=true 啟用多個現用結果集,否則這項作業將會失敗。This operation will fail unless you have enabled multiple active results sets by specifying multipleactiveresultsets=true in the connection string. 您也可以將查詢的結果載入 List<T> 集合中。You can also load the result of the query into a List<T> collection. 這樣會關閉資料讀取器,並且讓您列舉集合,以便載入參考的物件。This closes the data reader and enables you to enumerate over the collection to load referenced objects.

EntityCollection<TEntity>.Load 方法會與 EntityReference<TEntity>.Load 方法同步處理。The EntityCollection<TEntity>.Load method is synchronized with the EntityReference<TEntity>.Load method.