如何:使用导航运算符导航关系

本主题演示如何使用 EntityCommand 对象针对概念模型执行命令,以及如何使用 RefType 检索 EntityDataReader 结果。

运行本示例中的代码

  1. AdventureWorks 销售模型添加到项目并将项目配置为使用实体框架。 有关详细信息,请参阅如何:使用实体数据模型向导

  2. 在应用程序的代码页中,添加以下 using 指令(在 Visual Basic 中为 Imports):

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.EntityClient;
    using System.Data.Metadata.Edm;
    
    Imports System.Collections.Generic
    Imports System.Collections
    Imports System.Data.Common
    Imports System.Data
    Imports System.IO
    Imports System.Data.SqlClient
    Imports System.Data.EntityClient
    Imports System.Data.Metadata.Edm
    
    

示例

以下示例显示如何通过使用 NAVIGATE 运算符导航实体 SQL 中的关系。 Navigate 运算符具有以下参数:实体的实例、关系-类型、关系的结束和关系的开始。 或者,可以仅向 Navigate 运算符传递实体的实例和关系类型。

using (EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities"))
{
    conn.Open();
    // Create an EntityCommand.
    using (EntityCommand cmd = conn.CreateCommand())
    {
        // Create an Entity SQL query.
        string esqlQuery =
            @"SELECT address.AddressID, (SELECT VALUE DEREF(soh) FROM
          NAVIGATE(address, AdventureWorksModel.FK_SalesOrderHeader_Address_BillToAddressID)
          AS soh) FROM AdventureWorksEntities.Addresses AS address";

        cmd.CommandText = esqlQuery;

        // Execute the command.
        using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
        {
            // Start reading.
            while (rdr.Read())
            {
                Console.WriteLine(rdr["AddressID"]);
            }
        }
    }
    conn.Close();
}
Using conn As New EntityConnection("name=AdventureWorksEntities")
    conn.Open()
    ' Create an EntityCommand. 
    Using cmd As EntityCommand = conn.CreateCommand()
        ' Create an Entity SQL query. 
        Dim esqlQuery As String = "SELECT address.AddressID, (SELECT VALUE DEREF(soh) FROM " & _
            " NAVIGATE(address, AdventureWorksModel.FK_SalesOrderHeader_Address_BillToAddressID) " & _
            " AS soh) FROM AdventureWorksEntities.Addresses AS address"


        cmd.CommandText = esqlQuery

        ' Execute the command. 
        Using rdr As DbDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
            ' Start reading. 
            While rdr.Read()
                Console.WriteLine(rdr("AddressID"))
            End While
        End Using
    End Using
    conn.Close()
End Using

请参阅