다음을 통해 공유


방법: EntityCollection의 쿼리 관련 개체(Entity Framework)

이 항목에서는 EntityCollection에서 관계 탐색 속성에 의해 반환된 관련 개체를 쿼리하는 방법의 예제를 보여 줍니다.

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

예제

이 예제에서는 특정 연락처 관련 SalesOrderHeader 개체의 컬렉션을 로드한 다음 LINQ 식을 사용하여 이미 발송되어 온라인으로 주문된 주문 목록을 반환합니다.

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

Using context As AdventureWorksEntities = _
    New AdventureWorksEntities()
    Try
        ' Get a specified customer by contact ID.
        Dim customer = (From customers In context.Contact _
            Where customers.ContactID = customerId _
            Select customers).First()

        ' Load the customer orders if not already loaded.
        If Not customer.SalesOrderHeader.IsLoaded Then
            customer.SalesOrderHeader.Load()
        End If

        ' Write the number of orders for the customer.
        Console.WriteLine("Customer '{0}' has placed {1} total orders.", _
            customer.LastName, customer.SalesOrderHeader.Count)

        ' Get the online orders that have shipped.
        Dim shippedOrders = _
        From order In customer.SalesOrderHeader _
            Where order.OnlineOrderFlag = True _
            And order.Status = 5 _
            Select order

        ' Write the number of orders placed online.
        Console.WriteLine("{0} orders placed online have been shipped.", _
            shippedOrders.Count())
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
// Specify the customer ID.
int customerId = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Get a specified customer by contact ID.
        var customer = (from customers in context.Contact
            where customers.ContactID == customerId 
            select customers).First();
        
        // Load the customer orders if not already loaded.
        if (!customer.SalesOrderHeader.IsLoaded)
        {
            customer.SalesOrderHeader.Load();
        }

        // Write the number of orders for the customer.
        Console.WriteLine("Customer '{0}' has placed {1} total orders.",
            customer.LastName, customer.SalesOrderHeader.Count);

        // Get the online orders that have shipped.
        var shippedOrders =
            from order in customer.SalesOrderHeader
            where order.OnlineOrderFlag == true
            && order.Status == 5
            select order;

        // Write the number of orders placed online.
        Console.WriteLine("{0} orders placed online have been shipped.",
            shippedOrders.Count());
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

이 예제에서는 SalesOrderHeader 개체 컬렉션에 대한 첫 번째 예제로 동일한 LINQ 쿼리를 사용합니다. 관련된 모든 개체를 컬렉션으로 초기에 로드하는 대신, CreateSourceQuery 메서드를 사용하여 쿼리에서 반환된 개체만 로드합니다. 그런 다음, SalesOrderHeader 관계 탐색 속성에 의해 반환된 EntityCollection에 대해 Load 메서드를 호출하여 나머지 관련 개체를 로드합니다.

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

Using context As AdventureWorksEntities = _
    New AdventureWorksEntities()
    Try
        ' Get a specified customer by contact ID.
        Dim customer = (From customers In context.Contact _
                        Where customers.ContactID = customerId _
                        Select customers).First()

        ' Use CreateSourceQuery to generate a query that returns 
        ' only the online orders that have shipped.
        Dim shippedOrders = _
        From orders In customer.SalesOrderHeader.CreateSourceQuery() _
            Where orders.OnlineOrderFlag = True _
            And orders.Status = 5 _
            Select orders

        ' Write the number of orders placed online.
        Console.WriteLine("{0} orders placed online have been shipped.", _
            shippedOrders.Count())

        ' Load the remaining orders for this customer.
        If Not customer.SalesOrderHeader.IsLoaded Then
            customer.SalesOrderHeader.Load()
        End If

        ' Write the number of total orders for the customer.
        Console.WriteLine("Customer '{0}' has placed {1} total orders.", _
            customer.LastName, customer.SalesOrderHeader.Count)

    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
// Specify the customer ID.
int customerId = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Get a specified customer by contact ID.
        var customer = (from customers in context.Contact
                        where customers.ContactID == customerId
                        select customers).First();

        // Use CreateSourceQuery to generate a query that returns 
        // only the online orders that have shipped.
        var shippedOrders =
            from orders in customer.SalesOrderHeader.CreateSourceQuery()
            where orders.OnlineOrderFlag == true
            && orders.Status == 5
            select orders;

        // Write the number of orders placed online.
        Console.WriteLine("{0} orders placed online have been shipped.",
            shippedOrders.Count());

        // Load the remaining orders for this customer.
        if (!customer.SalesOrderHeader.IsLoaded)
        {
            customer.SalesOrderHeader.Load();
        }

        // Write the number of total orders for the customer.
        Console.WriteLine("Customer '{0}' has placed {1} total orders.",
            customer.LastName, customer.SalesOrderHeader.Count);
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

참고 항목

작업

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

개념

쿼리 결과 셰이핑(Entity Framework)