Share via


方法: 関連するオブジェクトを明示的に読み込む (Entity Framework)

このトピックでは、関連するオブジェクトを明示的に読み込む方法の例を紹介します。

最初の例では、EntityCollectionLoad メソッドを使用して、単一の顧客のすべての注文と品目を明示的に読み込みます。 POCO エンティティのナビゲーション プロパティは EntityCollection を返す必要がないため、Load メソッドを POCO エンティティと共に使用することはできません。 詳細については、「関連 POCO エンティティの読み込み (Entity Framework)」を参照してください。

2 つ目の例では、CreateSourceQuery メソッドを使用して、選択した注文だけを関連の品目と共に読み込むクエリを作成します。 これらの注文は、顧客にアタッチされます。

また、ObjectContext クラスの LoadProperty メソッドを使用して、関連オブジェクトを読み込むこともできます。 LoadProperty メソッドは、POCO エンティティ、および EntityObject から派生するエンティティと共に使用できます。

このトピックの例には、Adventure Works Sales Model が使用されています。 詳細については、「Entity Data Model ウィザードを使用する方法 (Entity Framework)」を参照してください。

次の例では、単一の Contact に属する SalesOrderHeader オブジェクトを読み込んでから、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()));
        }
    }
}

次の例では、EntityCollectionCreateSourceQuery メソッドを使用して、単一の 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()));
        }
    }
}

参照

処理手順

方法: エンティティ型オブジェクトを返すクエリを実行する (Entity Framework)
方法: クエリ パスを使用して結果を構築する (Entity Framework)
ナビゲーション プロパティを使用してリレーションシップをナビゲートする方法 (Entity Framework)

概念

関連オブジェクトの読み込み (Entity Framework)