Compartir a través de


How to: Query Related Objects in an EntityCollection (Entity Framework)

This topic provides examples of how to query related objects in an EntityCollection returned by the relationship navigation property.

The example in this topic is based on the Adventure Works Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework). You can also use the Entity Data Model Wizard to define the AdventureWorks Sales Model. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework).

Example

This example loads the collection of SalesOrderHeader objects related to a specific contact, and then uses a LINQ expression to return a list of orders placed online that have already shipped.

' Specify the customer ID.
Dim customerId = 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());
    }
}

This example uses the same LINQ query as the first example against the collection of SalesOrderHeader objects. Instead of initially loading all related objects into the collection, the CreateSourceQuery method is used to load only the objects returned by the query. The Load method is then called on the EntityCollection returned by the SalesOrderHeader relationship navigation property to load the remaining related objects.

' Specify the customer ID.
Dim customerId = 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());
    }
}

See Also

Tasks

How to: Execute a Query that Returns an Entity Type (Entity Framework)
How to: Use Query Paths to Shape Results (Entity Framework)
How to: Navigate Relationships Using Navigation Properties (Entity Framework)

Concepts

Shaping Query Results (Entity Framework)