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

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

Пример в этом разделе основан на модели Adventure Works Sales. Чтобы запустить код, используемый в данном примере, необходимо сначала добавить к проекту модель AdventureWorks Sales и настроить проект на использование платформы Entity Framework . Для этого выполните инструкции из разделов Как вручную настроить проект Entity Framework и Как определить модель и файлы сопоставления вручную (платформа Entity Framework). Для определения модели AdventureWorks Sales можно также использовать мастер моделей EDM. Дополнительные сведения см. в разделе Как использовать мастер моделей EDM (платформа Entity Framework).

Пример

В данном примере загружается коллекция объектов SalesOrderHeader, связанных с конкретным контактным лицом, а затем используется выражение LINQ для возврата списка заказов, размещенных в оперативном режиме, поставка по которым уже произведена.

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

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

    ' You do not have to call the Load method to load the orders for the customer, 
    ' because lazy loading is set to true 
    ' by the constructor of the AdventureWorksEntities object. 
    ' With lazy loading set to true the related objects are loaded when 
    ' you access the navigation property. In this case SalesOrderHeaders. 

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

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

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

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

    // You do not have to call the Load method to load the orders for the customer,
    // because  lazy loading is set to true 
    // by the constructor of the AdventureWorksEntities object. 
    // With  lazy loading set to true the related objects are loaded when
    // you access the navigation property. In this case SalesOrderHeaders.

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

    // Get the online orders that have shipped.
    var shippedOrders =
        from order in customer.SalesOrderHeaders
        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());
}

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

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

Using context As New AdventureWorksEntities()
    ' Get a specified customer by contact ID. 
    Dim customer = (From customers In context.Contacts
        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.SalesOrderHeaders.CreateSourceQuery() _
        Where orders.OnlineOrderFlag = True AndAlso orders.Status = 5 _
        Select orders

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

    ' You do not have to call the Load method to load the orders for the customer, 
    ' because lazy loading is set to true 
    ' by the constructor of the AdventureWorksEntities object. 
    ' With lazy loading set to true the related objects are loaded when 
    ' you access the navigation property. In this case SalesOrderHeaders. 

    ' Write the number of total orders for the customer. 
    Console.WriteLine("Customer '{0}' has placed {1} total orders.", _
                      customer.LastName, customer.SalesOrderHeaders.Count)
End Using
// Specify the customer ID.
int customerId = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Get a specified customer by contact ID.
    var customer = (from customers in context.Contacts
                    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.SalesOrderHeaders.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());

    // You do not have to call the Load method to load the orders for the customer,
    // because  lazy loading is set to true 
    // by the constructor of the AdventureWorksEntities object. 
    // With  lazy loading set to true the related objects are loaded when
    // you access the navigation property. In this case SalesOrderHeaders.

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

См. также

Задачи

Как выполнить запрос, возвращающий объекты типа сущностей (платформа Entity Framework)
Как использовать пути запросов для формирования результатов (платформа Entity Framework)
Как переходить по связям с помощью свойств навигации (платформа Entity Framework)

Основные понятия

Загрузка связанных объектов (платформа Entity Framework)