Partilhar via


How to: Explicitly Load Related Objects

This topic provides examples of how to explicitly load related objects.

The first example uses the Load method on EntityCollection to explicitly load all orders and items for a single customer. The Load method cannot be used with POCO entities because the navigation properties of POCO entities are not required to return EntityCollection. For more information, see Loading Related POCO Entities.

The second example uses the CreateSourceQuery method to create a query that loads only selected orders with the related items. These orders are then attached to the customer.

You could also use the LoadProperty method of the ObjectContext class to load related objects. The LoadProperty method can be used with POCO entities and with entities derived from EntityObject.

The examples in this topic are based on the Adventure Works Sales Model. For more information, see How to: Use the Entity Data Model Wizard.

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 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()));
        }
    }
}

The following example uses the CreateSourceQuery method on the EntityCollection to only load five SalesOrderHeader objects, with related SalesOrderDetail objects, that belong to a single Contact. This query result is then attached to the original 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()));
        }
    }
}

See Also

Tasks

How to: Execute a Query that Returns Entity Type Objects
How to: Use Query Paths to Shape Results
How to: Navigate Relationships Using Navigation Properties

Concepts

Loading Related Objects