如何:使用导航运算符导航关系 (EntityClient)
本主题提供一个示例,该示例演示如何使用 EntityCommand 对实体数据模型执行命令,以及如何使用 EntityDataReader 检索 RefType 结果。
运行本示例中的代码
将 AdventureWorks 销售模型添加到项目并将项目配置为使用实体框架。为此,请执行下列操作之一:
如果已安装实体数据模型工具,请完成如何:使用实体数据模型向导(实体框架) 中的过程。
否则,请完成如何:手动配置实体框架项目和如何:手动定义实体数据模型(实体框架) 中的过程。
在应用程序的代码页中,添加以下 using 语句(在 Visual Basic 中为 Imports):
Imports System Imports System.Collections.Generic Imports System.Collections Imports System.Data.Common Imports System.Data Imports System.Data.SqlClient Imports System.Data.EntityClient Imports System.Data.Metadata.Edm Imports System.IO ' Add AdventureWorksModel prepended with the root namespace for the project. 'Imports ProjectName.AdventureWorksModel
using System; using System.Collections.Generic; using System.Collections; using System.Data.Common; using System.Data; using System.IO; using System.Data.SqlClient; using System.Data.EntityClient; using AdventureWorksModel; using System.Data.Metadata.Edm;
示例
以下示例显示如何通过使用 NAVIGATE (Entity SQL) 运算符导航 Entity SQL 中的关系。Navigate 运算符具有以下参数:实体的实例、关系-类型、关系的结束和关系的开始。Navigate 运算符的简化版本具有实体的实例和关系-类型。以下示例说明如何使用 Navigate 运算符的简化版本。
Using connection As EntityConnection = New EntityConnection("name=AdventureWorksEntities")
connection.Open()
Try
' Create an EntityCommand and pass the connection object
' and Entity SQL query to its constructor.
Using cmd As EntityCommand = connection.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.Address AS address"
cmd.CommandText = esqlQuery
' Execute the command.
Using reader As DbDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
' Start reading.
Do While reader.Read
Console.WriteLine(reader.Item("AddressID"))
Loop
End Using
End Using
Catch ex As EntityException
Console.WriteLine(ex.ToString())
End Try
connection.Close()
End Using
using (EntityConnection conn =
new EntityConnection("name=AdventureWorksEntities"))
{
conn.Open();
try
{
// 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.Address AS address";
cmd.CommandText = esqlQuery;
// Execute the command.
using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
// Start reading.
while (rdr.Read())
{
Console.WriteLine(rdr["AddressID"]);
}
}
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
}
另请参见
概念
其他资源
使用 EntityClient(实体框架任务)
How to: Execute an Entity SQL Query Using EntityCommand