共用方式為


HOW TO:明確載入 POCO 實體 (Entity Framework)

本主題中的範例為您示範如何使用 ObjectContext 上的 LoadProperty 方法來明確載入相關物件。 如需使用消極式載入來存取相關物件的範例,請參閱 HOW TO:使用消極式載入來載入相關物件 (Entity Framework)LoadProperty 方法可以搭配 POCO 實體和衍生自 EntityObject 的實體使用。

本主題中的範例使用 HOW TO:定義 POCO 實體 (Entity Framework) 中所定義之 POCO 資料類別、在 HOW TO:定義自訂物件內容 (Entity Framework) 中建立的 AdventureWorksEntities 類別 (衍生自 ObjectContext),以及 HOW TO:自訂模型與對應檔以搭配自訂物件運作 (Entity Framework) 中所定義之 AdventureWorks 架構資料模型。

範例

本範例會傳回前五個 Order 物件,並呼叫 LoadProperty 方法,來為每個 Order 明確載入相關的 LineItem 物件。

Using context As New POCOAdventureWorksEntities()
    Try
        ' Disable lazy loading. 
        context.ContextOptions.LazyLoadingEnabled = False

        ' Get the first five orders. 
        For Each order As Order In context.Orders.Take(5)
            ' Because LazyLoadingEnabled is set to false, 
            ' we need to explicitly load the related line items for the order. 
            context.LoadProperty(order, "LineItems")

            Console.WriteLine(String.Format("PO Number: {0}", order.ExtendedInfo.PurchaseOrderNumber))
            Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
            Console.WriteLine("Order items:")
            For Each item As LineItem In order.LineItems
                Console.WriteLine(String.Format("Product: {0} " & "Quantity: {1}", item.ProductID, item.OrderQty))
            Next
        Next
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.Message)
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
End Using
using (POCOAdventureWorksEntities context =
        new POCOAdventureWorksEntities())
{
    try
    {
        // Disable lazy loading.
        context.ContextOptions.LazyLoadingEnabled = false;

        // Get the first five orders.
        foreach (Order order in context.Orders.Take(5))
        {
            // Because LazyLoadingEnabled is set to false,
            // we need to explicitly load the related line items for the order.
            context.LoadProperty(order, "LineItems");

            Console.WriteLine(String.Format("PO Number: {0}",
                order.ExtendedInfo.PurchaseOrderNumber));
            Console.WriteLine(String.Format("Order Date: {0}",
                order.OrderDate.ToString()));
            Console.WriteLine("Order items:");
            foreach (LineItem item in order.LineItems)
            {
                Console.WriteLine(String.Format("Product: {0} "
                    + "Quantity: {1}", item.ProductID,
                    item.OrderQty));
            }
        }
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

另請參閱

概念

載入相關的 POCO 實體 (Entity Framework)
自訂物件 (Entity Framework)
使用 POCO 實體 (Entity Framework)