Export (0) Print
Expand All

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.
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.
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

Community Additions

Show:
© 2014 Microsoft