Cómo consultar objetos relacionados en una EntityCollection (Entity Framework)

En este tema se proporcionan ejemplos de cómo consultar objetos relacionados en una EntityCollection devuelta por la propiedad de navegación de relación.

El ejemplo de este tema se basa en el modelo Adventure Works Sales. Para ejecutar el código de este ejemplo, debe haber agregado ya el modelo AdventureWorks Sales al proyecto y haber configurado el proyecto para usar Entity Framework . Para ello, complete los procedimientos de Cómo configurar manualmente un proyecto de Entity Framework y Cómo: Definir manualmente los archivos de asignación y modelo (Entity Framework). También puede utilizar el Asistente para Entity Data Model con el fin de definir el modelo AdventureWorks Sales. Para obtener más información, vea Cómo usar el Asistente para Entity Data Model (Entity Framework).

Ejemplo

En este ejemplo, se carga la colección de objetos SalesOrderHeader relacionada con un contacto concreto y, a continuación, se usa una expresión LINQ para devolver una lista de los pedidos realizados en línea que ya se han enviado.

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

En este ejemplo, se usa la misma consulta LINQ que en el primer ejemplo, donde la consulta se realiza en la colección de objetos SalesOrderHeader. En lugar de cargar inicialmente todos los objetos relacionados en la colección, se usa el método CreateSourceQuery para cargar solo los objetos devueltos por la consulta. A continuación, se llama al método Load de la EntityCollection devuelta por la propiedad de navegación de relación de SalesOrderHeader para cargar los objetos relacionados restantes.

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

Vea también

Tareas

Cómo: Ejecutar una consulta que devuelva objetos de tipo de entidad (Entity Framework)
Cómo: Usar rutas de la consulta para dar forma a los resultados (Entity Framework)
Cómo navegar por las relaciones mediante propiedades de navegación (Entity Framework)

Conceptos

Cargar objetos relacionados (Entity Framework)