Поделиться через


How to: Navigate Relationships Using Navigation Properties (Entity Framework)

This topic shows how to navigate relationships through navigation properties. For more information, see Navigation Properties (EDM). The example gets all the orders of the contacts whose last name is "Zhou". The Contact.SalesOrderHeader navigation property is used to get the collection of SalesOrderHeader objects for each contact. The same example is shown using each of the following Entity Framework query technologies:

  • LINQ to Entities

  • Entity SQL with ObjectQuery<T>

  • Query builder methods of ObjectQuery<T>

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 is the LINQ to Entities example.

Using AWEntities As New AdventureWorksEntities
    Dim contacts As ObjectQuery(Of Contact) = AWEntities.Contact

    Dim ordersQuery = From contact In contacts _
        Where contact.LastName = "Zhou" _
        Select New With _
                {.LastName = contact.LastName, _
                 .Orders = contact.SalesOrderHeader}

    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
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Contact> contacts = AWEntities.Contact;

    var ordersQuery = from contact in contacts
                      where contact.LastName == "Zhou"
                      select new { LastName = contact.LastName, Orders = contact.SalesOrderHeader };

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

This is the Entity SQL example.

Using advWorksContext As New AdventureWorksEntities
    Dim esqlQuery As String = "SELECT c.FirstName, c.SalesOrderHeader " & _
            " FROM AdventureWorksEntities.Contact AS c where c.LastName = 'Zhou'"
    Try
        Dim objQuery As New ObjectQuery(Of DbDataRecord)(esqlQuery, advWorksContext)
        For Each rec As DbDataRecord In objQuery
            ' Display contact's first name.
            Console.WriteLine("First Name {0}: ", rec.Item(0))
            Dim list As List(Of SalesOrderHeader) = DirectCast(rec.Item(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
    Catch ex As EntityException
        Console.WriteLine(ex.ToString())
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    string esqlQuery = @"SELECT c.FirstName, c.SalesOrderHeader 
        FROM AdventureWorksEntities.Contact AS c where c.LastName = 'Zhou'";

    try
    {
        foreach (DbDataRecord rec in
            new ObjectQuery<DbDataRecord>(esqlQuery, advWorksContext))
        {

            // 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);
            }
        }
    }
    catch (EntityException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

This is the query builder method example.

Using advWorksContext As New AdventureWorksEntities()
    Try
        ' Define a query that returns a nested 
        ' DbDataRecord for the projection.
        Dim query As ObjectQuery(Of DbDataRecord) = _
            advWorksContext.Contact.Select("it.FirstName, " _
                & "it.LastName, it.SalesOrderHeader") _
            .Where("it.LastName = 'Zhou'")

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

            ' Display contact's first name.
            Console.WriteLine("First Name {0}: ", rec(0))

            ' Display SalesOrderHeader information 
            ' associated with the contact.
            For Each soh As SalesOrderHeader In CType(rec(2), List(Of SalesOrderHeader))
                Console.WriteLine("   Order ID: {0}, " _
                    & "Order date: {1}, Total Due: {2}", _
                    soh.SalesOrderID, soh.OrderDate, soh.TotalDue)
            Next
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        // Define a query that returns a nested 
        // DbDataRecord for the projection.
        ObjectQuery<DbDataRecord> query =
            advWorksContext.Contact.Select("it.FirstName, "
                + "it.LastName, it.SalesOrderHeader")
            .Where("it.LastName = 'Zhou'");

        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);
            }
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

See Also

Tasks

How to: Use Query Paths to Shape Results (Entity Framework)

Concepts

Entity Data Model Relationships

Other Resources

Querying an Entity Data Model (Entity Framework Tasks)