Share via


Procedura: eseguire una query sugli oggetti correlati in un oggetto EntityCollection (Entity Framework)

In questo argomento vengono forniti esempi di come eseguire una query sugli oggetti correlati in un oggetto EntityCollection restituito dalla proprietà di navigazione della relazione.

L'esempio incluso in questo argomento è basato sul modello Sales di AdventureWorks. Per eseguire il codice incluso in questo esempio, è necessario avere già aggiunto il modello Sales di AdventureWorks al progetto e avere configurato il progetto per l'utilizzo di Entity Framework. A tale scopo, completare le procedure descritte in Procedura: configurare manualmente un progetto di Entity Framework e Procedura: definire manualmente un modello EDM (Entity Framework). È inoltre possibile utilizzare la procedura guidata Entity Data Model per definire il modello Sales di AdventureWorks. Per ulteriori informazioni, vedere Procedura: utilizzare la procedura guidata Entity Data Model (Entity Framework).

Esempio

In questo esempio viene caricato l'insieme di oggetti SalesOrderHeader correlati a un contatto specifico, quindi viene utilizzata un'espressione LINQ per restituire un elenco degli ordini effettuati in linea già spediti.

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

In questo esempio viene utilizzata la stessa query LINQ del primo esempio sull'insieme di oggetti SalesOrderHeader. Anziché caricare inizialmente tutti gli oggetti correlati nell'insieme, viene utilizzato il metodo CreateSourceQuery per caricare solo gli oggetti restituiti dalla query. Il metodo Load viene quindi chiamato sull'oggetto EntityCollection restituito dalla proprietà di navigazione della relazione SalesOrderHeader per caricare gli oggetti correlati rimanenti.

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

Vedere anche

Attività

Procedura: eseguire una query che restituisce un tipo di entità (Entity Framework)
Procedura: utilizzare percorsi di query per influenzare i risultati (Entity Framework)
Procedura: spostarsi nelle relazioni utilizzando le proprietà di navigazione (Entity Framework)

Concetti

Determinazione della struttura dei risultati di query (Entity Framework)