如何:使用导航属性导航关系(实体框架)

本主题说明如何通过导航属性来导航关系。有关更多信息,请参见导航属性 (EDM)。此示例获取其姓氏为“Zhou”的联系人的所有订单。Contact.SalesOrderHeader 导航属性用于获取每个联系人的 SalesOrderHeader 对象的集合。将使用以下每种 实体框架 查询技术演示同一示例:

  • LINQ to Entities

  • Entity SQL with ObjectQuery<T>

  • ObjectQuery<T> 的查询生成器方法

本主题中的示例基于 Adventure Works 销售模型。若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用 实体框架。为此,请完成如何:手动配置实体框架项目如何:手动定义实体数据模型(实体框架) 中的过程。也可以使用实体数据模型向导定义 AdventureWorks 销售模型。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)

示例

这是 LINQ to Entities 示例。

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

这是 Entity SQL 示例。

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

这是查询生成器方法示例。

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

另请参见

任务

如何:使用查询路径调整结果(实体框架)

概念

实体数据模型关系

其他资源

查询实体数据模型(实体框架任务)