Export (0) Print
Expand All
Expand Minimize

How to: Explicitly Load POCO Entities

.NET Framework 4

The examples in this topic show you how to explicitly load related objects by using the LoadProperty method on the ObjectContext. For an example of using lazy loading to access related objects, see How to: Use Lazy Loading to Load Related Objects. The LoadProperty method can be used with POCO entities and with entities that derive from EntityObject.

The examples in this topic use the POCO data classes that are defined in How to: Define POCO Entities, the AdventureWorksEntities class (derived from ObjectContext) that is created in How to: Define a Custom Object Context, and an AdventureWorks-based data model that is defined in How to: Customize Modeling and Mapping Files to Work with Custom Objects.


This example returns the first five Order objects and calls the LoadProperty method to explicitly load the related LineItem objects for each Order.

using (POCOAdventureWorksEntities context =
        new POCOAdventureWorksEntities())
        // Disable lazy loading.
        context.ContextOptions.LazyLoadingEnabled = false;

        // Get the first five orders.
        foreach (Order order in context.Orders.Take(5))
            // Because LazyLoadingEnabled is set to false,
            // we need to explicitly load the related line items for the order.
            context.LoadProperty(order, "LineItems");

            Console.WriteLine(String.Format("PO Number: {0}",
            Console.WriteLine(String.Format("Order Date: {0}",
            Console.WriteLine("Order items:");
            foreach (LineItem item in order.LineItems)
                Console.WriteLine(String.Format("Product: {0} "
                    + "Quantity: {1}", item.ProductID,
    catch (InvalidOperationException ex)
    catch (Exception ex)

See Also

Community Additions

© 2014 Microsoft