Как выполнять запросы к связанным объектам в коллекции EntityCollection (платформа Entity Framework)

В этом разделе приведены примеры того, как выполнить запрос к связанным объектам в коллекции EntityCollection, возвращаемой свойством навигации связи.

Пример в этом разделе основан на модели Adventure Works Sales. Чтобы запустить код, используемый в данном примере, нужно сначала добавить к проекту модель AdventureWorks Sales и настроить его для использования платформы Entity Framework. Для этого выполните инструкции из разделов Как вручную настроить проект Entity Framework и Как определить модель EDM вручную (платформа Entity Framework). Для определения модели AdventureWorks Sales можно также использовать мастер моделей EDM. Дополнительные сведения см. в разделе Как использовать мастер моделей EDM (платформа 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());
    }
}

В этом примере используется тот же запрос LINQ, что и в первом примере, применительно к коллекции объектов SalesOrderHeader. Вместо первоначальной загрузки всех связанных объектов в коллекцию метод CreateSourceQuery используется для загрузки только тех объектов, которые возвращены запросом. После этого вызывается метод Load применительно к коллекции EntityCollection, возвращенной свойством навигации по связи SalesOrderHeader, для загрузки оставшихся связанных объектов.

' 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)