Share via


방법: 지연 로드를 사용하여 관련 개체 로드(Entity Framework)

이 항목에서는 지연 로드를 사용하여 관련 개체를 로드하는 방법을 보여 줍니다. 지연 로드를 사용하면 탐색 속성을 통해 관련 개체에 액세스할 때 해당 개체가 로드됩니다. Include 메서드를 사용하여 개체를 즉시 로드하거나 LoadProperty 메서드를 사용하여 개체를 명시적으로 로드할 수도 있습니다. 자세한 내용은 관련 개체 로드(Entity Framework)를 참조하십시오.

Entity Framework 런타임에서 ObjectContext 인스턴스에 있는 LazyLoadingEnabled 속성의 기본값은 false입니다. 그러나 Entity Framework 도구를 사용하여 새 모델 및 생성된 해당 클래스를 만드는 경우, 생성된 코드에서는 생성된 개체 컨텍스트의 생성자에서 LazyLoadingEnabledtrue로 설정합니다.

이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 항목의 코드를 실행하려면 프로젝트에 Adventure Works Sales 모델을 추가하고 프로젝트에서 Entity Framework를 사용하도록 구성해야 합니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework) 또는 방법: Entity Framework 프로젝트 수동 구성방법: 엔터티 데이터 모델 수동 정의(Entity Framework)를 참조하십시오.

예제

다음 예제에서는 10개의 연락처를 표시하고 사용자를 그 중 하나를 선택할 수 있도록 합니다. 그런 다음 선택한 연락처에 따라 관련 주문이 로드됩니다.

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

참고 항목

작업

방법: 쿼리 경로를 사용하여 결과 셰이핑(Entity Framework)
방법: 명시적으로 관련 개체 로드(Entity Framework)

개념

관련 개체 로드(Entity Framework)
관련 POCO 엔터티 로드(Entity Framework)