This documentation is archived and is not being maintained.

How to: Use Lazy Loading to Load Related Objects

Visual Studio 2010

This topic shows how to use lazy loading to load related objects. With lazy loading enabled, related objects are loaded when they are accessed through a navigation property. You can still eagerly load objects with the Include method or explicitly load them with the LoadProperty method. For more information, see Loading Related Objects.

In the Entity Framework runtime, the default value of the LazyLoadingEnabled property in an instance of ObjectContext is false. However, if you use the Entity Framework tools to create a new model and the corresponding generated classes, the generated code will set LazyLoadingEnabled to true in the constructor of the generated object context.

The example in this topic is based on the Adventure Works Sales Model. To run the code in this topic, you must have already added the Adventure Works Sales Model to your project and configured your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework) or How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).

Example

The following example displays ten contacts and lets the user select one. Based on the selected contact the related orders are then loaded.

class LazyLoading
{
    public void EnableLazyLoading()
    {
        using (AdventureWorksEntities context =
            new AdventureWorksEntities())
        {
            // You do not have to set context.ContextOptions.LazyLoadingEnabled to true 
            // if you used the Entity Framework to generate the object layer.
            // The generated object context type sets lazy loading to true
            // in the constructor. 
            context.ContextOptions.LazyLoadingEnabled = true;

            // Display ten contacts and select a contact
            var contacts = context.Contacts.Take(10);
            foreach (var c in contacts)
                Console.WriteLine(c.ContactID);

            Console.WriteLine("Select a customer:");
            Int32 contactID = Convert.ToInt32(Console.ReadLine());

            // Get a specified customer by contact ID. 
            var contact = context.Contacts.Where(c => c.ContactID == contactID).FirstOrDefault();

            // If lazy loading was not enabled no SalesOrderHeaders would be loaded for the contact.
            foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
            {
                Console.WriteLine("SalesOrderID: {0} Order Date: {1} ",
                    order.SalesOrderID, order.OrderDate);
            }
        }
    }
}

See Also

Show: