다음을 통해 공유


방법: 명시적으로 관련 개체 로드(Entity Framework)

이 항목에서는 관련 개체를 명시적으로 로드하는 방법에 대한 예제를 제공합니다.

첫 번째 예제에서는 EntityCollectionLoad 메서드를 사용하여 단일 고객의 모든 주문과 항목을 명시적으로 로드합니다. POCO 엔터티의 탐색 속성은 EntityCollection을 반환할 필요가 없으므로 Load 메서드를 POCO 엔터티와 함께 사용할 수 없습니다. 자세한 내용은 관련 POCO 엔터티 로드(Entity Framework)를 참조하십시오.

두 번째 예제에서는 CreateSourceQuery 메서드를 사용하여 관련 항목이 있는 선택한 주문만 로드하는 쿼리를 만듭니다. 이러한 주문은 고객에 연결됩니다.

ObjectContext 클래스의 LoadProperty 메서드를 사용하여 관련 개체를 로드할 수도 있습니다. LoadProperty 메서드는 POCO 엔터티 및 EntityObject에서 파생된 엔터티와 함께 사용할 수 있습니다.

이 항목의 예제는 AdventureWorks Sales 모델을 기반으로 합니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework)을 참조하십시오.

예제

다음 예제에서는 단일 Contact에 속하는 SalesOrderHeader 개체를 로드한 다음 EntityCollectionSalesOrderHeader 개체를 반복합니다. 컬렉션의 각 SalesOrderHeader 개체에서 Load 메서드는 데이터베이스에서 관련 SalesOrderDetail 개체의 컬렉션을 검색하기 위해 호출됩니다.

' Specify the customer ID. 
Dim contactID As Integer = 4332

Using context As New AdventureWorksEntities()
    context.ContextOptions.LazyLoadingEnabled = False

    ' Get a specified customer by contact ID. 
    Dim contact = (From c In context.Contacts
        Where c.ContactID = contactID
        Select c).First()

    ' Load the orders for the customer explicitly. 
    If Not contact.SalesOrderHeaders.IsLoaded Then
        contact.SalesOrderHeaders.Load()
    End If

    For Each order As SalesOrderHeader In contact.SalesOrderHeaders
        ' Load the items for the order if not already loaded. 
        If Not order.SalesOrderDetails.IsLoaded Then
            order.SalesOrderDetails.Load()
        End If

        Console.WriteLine(String.Format("PO Number: {0}", order.PurchaseOrderNumber))
        Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
        Console.WriteLine("Order items:")
        For Each item As SalesOrderDetail In order.SalesOrderDetails
            Console.WriteLine(String.Format("Product: {0} Quantity: {1}", _
                                              item.ProductID.ToString(), item.OrderQty.ToString()))
        Next
    Next
End Using
// Specify the customer ID.
int contactID = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    context.ContextOptions.LazyLoadingEnabled = false;

    // Get a specified customer by contact ID.
    var contact =
        (from c in context.Contacts
         where c.ContactID == contactID
         select c).First();

    // Load the orders for the customer explicitly.
    if (!contact.SalesOrderHeaders.IsLoaded)
    {
        contact.SalesOrderHeaders.Load();
    }

    foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
    {
        // Load the items for the order if not already loaded.
        if (!order.SalesOrderDetails.IsLoaded)
        {
            order.SalesOrderDetails.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.SalesOrderDetails)
        {
            Console.WriteLine(String.Format("Product: {0} "
                + "Quantity: {1}", item.ProductID.ToString(),
                item.OrderQty.ToString()));
        }
    }
}

다음 예제에서는 EntityCollectionCreateSourceQuery 메서드를 사용하여 단일 Contact에 속하며 관련된 SalesOrderDetail 개체가 있는 다섯 개의 SalesOrderHeader 개체만 로드합니다. 그런 다음 이 쿼리 결과는 원래 SalesOrderHeader EntityCollection에 연결됩니다.

' Specify the customer ID. 
Dim customerId As Integer = 4332

Using context As New AdventureWorksEntities()
    ' Get a specified customer by contact ID. 
    Dim customer As Contact = context.Contacts.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.SalesOrderHeaders.Attach(customer.SalesOrderHeaders.CreateSourceQuery().Include("SalesOrderDetails").Take(5))

    For Each order As SalesOrderHeader In customer.SalesOrderHeaders
        Console.WriteLine(String.Format("PO Number: {0}", order.PurchaseOrderNumber))
        Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
        Console.WriteLine("Order items:")

        For Each item As SalesOrderDetail In order.SalesOrderDetails
            Console.WriteLine(String.Format("Product: {0} Quantity: {1}", _
                                              item.ProductID.ToString(), item.OrderQty.ToString()))
        Next
    Next
End Using
// Specify the customer ID.
int customerId = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Get a specified customer by contact ID.
    Contact customer = context.Contacts
        .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.SalesOrderHeaders.Attach(
        customer.SalesOrderHeaders.CreateSourceQuery()
        .Include("SalesOrderDetails").Take(5));

    foreach (SalesOrderHeader order in customer.SalesOrderHeaders)
    {
        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.SalesOrderDetails)
        {
            Console.WriteLine(String.Format("Product: {0} "
                + "Quantity: {1}", item.ProductID.ToString(),
                item.OrderQty.ToString()));
        }
    }
}

참고 항목

작업

방법: 엔터티 형식 개체를 반환하는 쿼리 실행(Entity Framework)
방법: 쿼리 경로를 사용하여 결과 셰이핑(Entity Framework)
방법: 탐색 속성을 사용하여 관계 탐색(Entity Framework)

개념

관련 개체 로드(Entity Framework)