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

このトピックでは、関連するオブジェクトを明示的に読み込む方法の例を紹介します。最初の例では、単一の顧客のすべての注文と品目を明示的に読み込みます。2 つ目の例では、別のクエリを使用して選択した注文だけを関連の品目と共に読み込みます。これらの注文は、顧客にアタッチされます。

このトピックの例には、AdventureWorks Sales Model が使用されています。このトピックのコードを実行するには、あらかじめプロジェクトに AdventureWorks Sales Model を追加し、エンティティ フレームワーク が使用されるようにプロジェクトを構成しておく必要があります。具体的な方法については、「Entity Framework プロジェクトを手動で構成する方法」および「Entity Data Model を手動で定義する方法 (Entity Framework)」の手順を参照してください。Entity Data Model ウィザードを使用して、AdventureWorks Sales Model を定義することもできます。詳細については、「Entity Data Model ウィザードを使用する方法 (Entity Framework)」を参照してください。

次の例では、単一の Contact に属する SalesOrderHeader オブジェクトを読み込んでから、EntityCollection 内の SalesOrderHeader オブジェクトを反復処理します。コレクション内の各 SalesOrderHeader オブジェクトについて、Load メソッドを呼び出し、関連する SalesOrderDetail オブジェクトのコレクションをデータベースから取得します。

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

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

        ' Load the orders for the customer
        If (Not customer.SalesOrderHeader.IsLoaded) Then
            customer.SalesOrderHeader.Load()
        End If

        For Each order As SalesOrderHeader In customer.SalesOrderHeader

            ' Load the items for the order if not already loaded.
            If Not order.SalesOrderDetail.IsLoaded Then
                order.SalesOrderDetail.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:")
            Dim item As SalesOrderDetail
            For Each item In order.SalesOrderDetail
                Console.WriteLine(String.Format("Product:{0}" _
                    + "Quantity: {1}", item.ProductID.ToString(), _
                    item.OrderQty.ToString()))
            Next
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    Catch ex As EntityCommandExecutionException
        Console.WriteLine(ex.ToString())
    End Try
End Using
// Specify the customer ID.
int customerId = 4332;

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

        // Load the orders for the customer
        if (!customer.SalesOrderHeader.IsLoaded)
        {
            customer.SalesOrderHeader.Load();
        }

        foreach (SalesOrderHeader order in customer.SalesOrderHeader)
        {
            // Load the items for the order if not already loaded.
            if (!order.SalesOrderDetail.IsLoaded)
            {
                order.SalesOrderDetail.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.SalesOrderDetail)
            {
                Console.WriteLine(String.Format("Product: {0} "
                    + "Quantity: {1}", item.ProductID.ToString(),
                    item.OrderQty.ToString()));
            }
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (EntityCommandExecutionException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

次の例では、EntityCollectionCreateSourceQuery メソッドを使用して、単一の Contact に属する 5 つの SalesOrderHeader オブジェクトだけを、関連の SalesOrderDetail オブジェクトと共に読み込みます。このクエリ結果は、元の SalesOrderHeaderEntityCollection にアタッチされます。

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

Using context As New AdventureWorksEntities 
    Try
        ' Get a specified customer by contact ID.
        Dim customer As Contact = context.Contact _
        .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.SalesOrderHeader.Attach( _
        customer.SalesOrderHeader.CreateSourceQuery() _
            .Include("SalesOrderDetail").Take(5))

        For Each order As SalesOrderHeader In customer.SalesOrderHeader
            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.SalesOrderDetail
                Console.WriteLine(String.Format("Product: {0} " _
                    + "Quantity: {1}", item.ProductID.ToString(), _
                    item.OrderQty.ToString()))
            Next
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
// Specify the customer ID.
int customerId = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Get a specified customer by contact ID.
        Contact customer = context.Contact
            .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.SalesOrderHeader.Attach(
            customer.SalesOrderHeader.CreateSourceQuery()
            .Include("SalesOrderDetail").Take(5));

        foreach (SalesOrderHeader order in customer.SalesOrderHeader)
        {
            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.SalesOrderDetail)
            {
                Console.WriteLine(String.Format("Product: {0} "    
                    + "Quantity: {1}", item.ProductID.ToString(),    
                    item.OrderQty.ToString()));
            }
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

参照

処理手順

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

概念

クエリ結果の構造化 (Entity Framework)