Welcome

首页 / 软件开发 / .NET编程技术 / Entity Data Model (EDM)深入分析, Part 3

Entity Data Model (EDM)深入分析, Part 32010-09-10EntLibEntityClient

实体框架(Entity Framework)在ADO.NET 3.5 提供程序的基础上引入新的 ADO.NET 提供程序 EntityClient。Entity­Client 看上去与之前使用的 ADO.NET 提供程序非常类似,它将提供第一个抽象,可允许开发人员使用标准的 Connection、Command 和 DataReader 对象依照 EDM 执行查询。它还会将映射域模型所需的客户端视图引擎(根据 EDM 定义的)添加到底层关系数据库架构。必要时,EntityClient 可借助 ESQL 查询字符串让开发人员以行和列的形式处理实体,而不必生成类来表示概念架构。

1. EntityCommand 查询返回实体类型

Entity SQL也可以通过EntityClient 来执行,尽管代码比较啰嗦,但是在某些情况下,也是优点。

1) 首先创建EntityConnection,重用Northwind data context 的连接字符串,并打开连接。

2) 创建 EntityCommand 对象,并传入Entity SQL语句和数据库连接对象。

3) 创建DbDataReader对象,并循环读取返回的结果集。

NorthwindEntities context = new NorthwindEntities();

EntityConnection conn = new EntityConnection(context.Connection.ConnectionString);
conn.Open();

var sql = "SELECT VALUE emp FROM NorthwindEntities.Employees AS emp";
EntityCommand cmd = new EntityCommand(sql, conn);

DbDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (reader.Read())
{
Console.WriteLine("{0} {1} {2} {3}", reader["EmployeeID"], reader["LastName"],
reader["FirstName"], reader["Country"]);
}

当时使用SequentialAccess的DbDataReader时,需要小心访问数据,务必有序的读取。

如你改变成员的顺序,将抛出InvalidOperationException 异常 - "Attempt to read from column ordinal "0" is not valid. With CommandBehavior.SequentialAccess, you may only read from column ordinal "2" or greater."

Console.WriteLine("{0} {1} {2} {3}", reader["LastName"], reader["EmployeeID"],
reader["FirstName"], reader["Country"]);

2. EntityCommand 查询返回匿名类型

采用相同的技术可以实现返回匿名类型。

EntityConnection conn = new EntityConnection(context.Connection.ConnectionString);
conn.Open();

var sql = "SELECT emp.LastName, emp.FirstName " +
"FROM NorthwindEntities.Employees AS emp";
EntityCommand cmd = new EntityCommand(sql, conn);

DbDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader["LastName"], reader["FirstName"]);
}