Share via


Procedura: spostarsi nelle relazioni utilizzando le proprietà di navigazione (Entity Framework)

In questo argomento viene illustrato come spostarsi nelle relazioni tramite le proprietà di navigazione. Per ulteriori informazioni, vedere Proprietà di navigazione. Nell'esempio vengono ottenuti tutti gli ordini dei contatti il cui cognome è "Zhou". La proprietà di navigazione Contact.SalesOrderHeader viene utilizzata per ottenere la raccolta di oggetti SalesOrderHeader per ciascun contatto. Lo stesso esempio viene illustrato utilizzando ognuna delle tecnologie di query Entity Framework seguenti:

  • LINQ to Entities

  • Entity SQL con ObjectQuery<T>

  • Metodi del generatore di query di ObjectQuery<T>

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

Esempio

Di seguito viene illustrato un esempio di LINQ to Entities .

Dim lastName = "Zhou"
Using context As New AdventureWorksEntities
    Dim contacts As ObjectSet(Of Contact) = context.Contacts

    Dim ordersQuery = From contact In contacts _
        Where contact.LastName = lastName _
        Select New With _
                {.LastName = contact.LastName, _
                 .Orders = contact.SalesOrderHeaders}

    For Each order In ordersQuery
        Console.WriteLine("Name: {0}", order.LastName)
        For Each orderInfo In order.Orders

            Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}", _
                    orderInfo.SalesOrderID, orderInfo.OrderDate, orderInfo.TotalDue)
        Next

        Console.WriteLine("")
    Next
End Using
string lastName = "Zhou";
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = context.Contacts;

    var ordersQuery = from contact in contacts
                      where contact.LastName == lastName
                      select new { LastName = contact.LastName, Orders = contact.SalesOrderHeaders };

    foreach (var order in ordersQuery)
    {
        Console.WriteLine("Name: {0}", order.LastName);
        foreach (SalesOrderHeader orderInfo in order.Orders)
        {
            Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}",
                orderInfo.SalesOrderID, orderInfo.OrderDate, orderInfo.TotalDue);
        }
        Console.WriteLine("");
    }
}

Di seguito viene illustrato un esempio di Entity SQL .

Using context As New AdventureWorksEntities()
    Dim esqlQuery As String = "SELECT c.FirstName, c.SalesOrderHeaders " & _
        " FROM AdventureWorksEntities.Contacts AS c where c.LastName = @ln"

    Dim query As New ObjectQuery(Of DbDataRecord)(esqlQuery, context)

    ' Add parameters to the collection. 
    query.Parameters.Add(New ObjectParameter("ln", "Zhou"))

    For Each rec As DbDataRecord In query

        ' Display contact's first name. 
        Console.WriteLine("First Name {0}: ", rec(0))
        Dim list As List(Of SalesOrderHeader) = TryCast(rec(1), List(Of SalesOrderHeader))
        ' Display SalesOrderHeader information 
        ' associated with the contact. 
        For Each soh As SalesOrderHeader In list
            Console.WriteLine(" Order ID: {0}, Order date: {1}, Total Due: {2}",
                              soh.SalesOrderID, soh.OrderDate, soh.TotalDue)
        Next
    Next
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    string esqlQuery = @"SELECT c.FirstName, c.SalesOrderHeaders 
        FROM AdventureWorksEntities.Contacts AS c where c.LastName = @ln";
    ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(esqlQuery, context);
    query.Parameters.Add(new ObjectParameter("ln", "Zhou"));

    foreach (DbDataRecord rec in query)
    {

        // Display contact's first name.
        Console.WriteLine("First Name {0}: ", rec[0]);
        List<SalesOrderHeader> list = rec[1] as List<SalesOrderHeader>;
        // Display SalesOrderHeader information 
        // associated with the contact.
        foreach (SalesOrderHeader soh in list)
        {
            Console.WriteLine("   Order ID: {0}, Order date: {1}, Total Due: {2}",
                soh.SalesOrderID, soh.OrderDate, soh.TotalDue);
        }
    }
}

Di seguito viene fornito un esempio del metodo del generatore di query.

Dim lastName = "Zhou"

Using context As New AdventureWorksEntities()
    ' Define a query that returns a nested 
    ' DbDataRecord for the projection. 
    Dim query As ObjectQuery(Of DbDataRecord) = context.Contacts.Select("it.FirstName, it.LastName, it.SalesOrderHeaders") _
                                                .Where("it.LastName = @ln", New ObjectParameter("ln", lastName))

    For Each rec As DbDataRecord In query.Execute(MergeOption.AppendOnly)

        ' Display contact's first name. 
        Console.WriteLine("First Name {0}: ", rec(0))
        Dim list As List(Of SalesOrderHeader) = TryCast(rec(2), List(Of SalesOrderHeader))
        ' Display SalesOrderHeader information 
        ' associated with the contact. 
        For Each soh As SalesOrderHeader In list
            Console.WriteLine(" Order ID: {0}, Order date: {1}, Total Due: {2}", _
                              soh.SalesOrderID, soh.OrderDate, soh.TotalDue)
        Next
    Next
End Using
string lastName = "Zhou";
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Define a query that returns a nested 
    // DbDataRecord for the projection.
    ObjectQuery<DbDataRecord> query =
        context.Contacts.Select("it.FirstName, "
            + "it.LastName, it.SalesOrderHeaders")
        .Where("it.LastName = @ln", new ObjectParameter("ln", lastName));

    foreach (DbDataRecord rec in
        query.Execute(MergeOption.AppendOnly))
    {

        // Display contact's first name.
        Console.WriteLine("First Name {0}: ", rec[0]);
        List<SalesOrderHeader> list = rec[2]
            as List<SalesOrderHeader>;
        // Display SalesOrderHeader information 
        // associated with the contact.
        foreach (SalesOrderHeader soh in list)
        {
            Console.WriteLine("   Order ID: {0}, " +
                "Order date: {1}, Total Due: {2}",
                soh.SalesOrderID, soh.OrderDate, soh.TotalDue);
        }
    }
}

Vedere anche

Attività

Procedura: utilizzare percorsi di query per influenzare i risultati (Entity Framework)

Concetti

Esecuzione di query su un modello concettuale (Entity Framework)
Definizione e gestione delle relazioni (Entity Framework)