HOW TO:明確載入相關的物件 (Entity Framework)

本主題提供的範例將說明如何明確載入相關的物件。

第一個範例會在 EntityCollection 上使用 Load,以明確載入單一客戶的所有訂單和項目。 Load 方法無法搭配 POCO 實體一起使用,因為傳回 EntityCollection 不需要 POCO 實體的導覽屬性。 如需詳細資訊,請參閱載入相關的 POCO 實體 (Entity Framework)

第二個範例會使用 CreateSourceQuery 方法來建立查詢,這個查詢只會載入選取的訂單與相關項目。 接著將這些訂單附加給客戶。

您也可以使用 ObjectContext 類別的 LoadProperty 方法,載入相關的物件。 LoadProperty 方法可以搭配 POCO 實體以及衍生自 EntityObject 的實體一起使用。

本主題的範例是根據 Adventure Works Sales Model。 如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework)

範例

下列範例會載入屬於單一 ContactSalesOrderHeader 物件,然後再逐一查看 EntityCollection 中的 SalesOrderHeader 物件。 對於集合中的每個 SalesOrderHeader 物件,會呼叫 Load 方法以從資料庫擷取相關 SalesOrderDetail 物件的集合。

' 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
        contact.SalesOrderHeaders.Load()
    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
            order.SalesOrderDetails.Load()
        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()))
        Next
    Next
End Using
// 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)
    {
        contact.SalesOrderHeaders.Load();
    }

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

        Console.WriteLine(String.Format("PO Number: {0}",
            order.PurchaseOrderNumber));
        Console.WriteLine(String.Format("Order Date: {0}",
            order.OrderDate.ToString()));
        Console.WriteLine("Order items:");
        foreach (SalesOrderDetail item in order.SalesOrderDetails)
        {
            Console.WriteLine(String.Format("Product: {0} "
                + "Quantity: {1}", item.ProductID.ToString(),
                item.OrderQty.ToString()));
        }
    }
}

下列範例會對 EntityCollection 使用 CreateSourceQuery 方法,只載入屬於單一 Contact 的 5 個 SalesOrderHeader 物件與相關 SalesOrderDetail 物件。 接著會將這個查詢結果附加到原始 SalesOrderHeader EntityCollection 中。

' Specify the customer ID. 
Dim customerId As Integer = 4332

Using context As New AdventureWorksEntities()
    ' Get a specified customer by contact ID. 
    Dim customer As Contact = context.Contacts.Where("it.ContactID = @customerId", _
                                                     New ObjectParameter("customerId", customerId)).First()

    ' Return the customer's first five orders with line items and 
    ' attach them to the SalesOrderHeader collection. 
    customer.SalesOrderHeaders.Attach(customer.SalesOrderHeaders.CreateSourceQuery().Include("SalesOrderDetails").Take(5))

    For Each order As SalesOrderHeader In customer.SalesOrderHeaders
        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()))
        Next
    Next
End Using
// Specify the customer ID.
int customerId = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Get a specified customer by contact ID.
    Contact customer = context.Contacts
        .Where("it.ContactID = @customerId",
        new ObjectParameter("customerId", customerId)).First();

    // Return the customer's first five orders with line items and
    // attach them to the SalesOrderHeader collection.
    customer.SalesOrderHeaders.Attach(
        customer.SalesOrderHeaders.CreateSourceQuery()
        .Include("SalesOrderDetails").Take(5));

    foreach (SalesOrderHeader order in customer.SalesOrderHeaders)
    {
        Console.WriteLine(String.Format("PO Number: {0}",
            order.PurchaseOrderNumber));
        Console.WriteLine(String.Format("Order Date: {0}",
            order.OrderDate.ToString()));
        Console.WriteLine("Order items:");

        foreach (SalesOrderDetail item in order.SalesOrderDetails)
        {
            Console.WriteLine(String.Format("Product: {0} "
                + "Quantity: {1}", item.ProductID.ToString(),
                item.OrderQty.ToString()));
        }
    }
}

另請參閱

工作

HOW TO:執行傳回實體類型物件的查詢 (Entity Framework)
HOW TO:使用查詢路徑來設定結果外觀 (Entity Framework)
HOW TO:使用導覽屬性巡覽關聯性 (Entity Framework)

概念

載入相關的物件 (Entity Framework)