Compartilhar via


How to: Explicitly Load Related Objects (Entity Framework)

This topic provides examples of how to explicitly load related objects. The first example explicitly loads all orders and items for a single customer. The second example uses a separate query to load only selected orders with the related items. These orders are then attached to the customer.

The examples in this topic are based on the Adventure Works Sales Model. To run the code in this topic, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework). You can also use the Entity Data Model Wizard to define the AdventureWorks Sales Model. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework).

Example

The following example loads SalesOrderHeader objects that belong to a single Contact and then iterates through the SalesOrderHeader objects in the EntityCollection. On each SalesOrderHeader object in the collection, the Load method is called to retrieve the collection of related SalesOrderDetail objects from the database.

' Specify the customer ID.
Dim customerId = 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());
    }
}

The following example uses the CreateSourceQuery method on the EntityCollection to only load five SalesOrderHeader objects, with related SalesOrderDetail object, that belong to a single Contact. This query result is then attached to original SalesOrderHeader EntityCollection.

' Specify the customer ID.
Dim customerId = 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());
    }
}

See Also

Tasks

How to: Execute a Query that Returns an Entity Type (Entity Framework)
How to: Use Query Paths to Shape Results (Entity Framework)
How to: Navigate Relationships Using Navigation Properties (Entity Framework)

Concepts

Shaping Query Results (Entity Framework)