Export (0) Print
Expand All
Expand Minimize

How to: Use Lazy Loading to Load Related Objects

.NET Framework 4

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 Sub EnableLazyLoading()
        Using context As 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 
            Dim contacts = context.Contacts.Take(10)
            For Each c In contacts
                Console.WriteLine(c.ContactID)
            Next

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

            ' Get a specified customer by contact ID. 
            Dim contact = context.Contacts.Where(Function(c) c.ContactID = contactID).FirstOrDefault()

            ' If lazy loading was not enabled no SalesOrderHeaders would be loaded for the contact. 
            For Each order As SalesOrderHeader In contact.SalesOrderHeaders
                Console.WriteLine("SalesOrderID: {0} Order Date: {1} ", order.SalesOrderID, order.OrderDate)
            Next
        End Using
    End Sub
End Class

See Also

Community Additions

ADD
Show:
© 2015 Microsoft