Welcome

首页 / 软件开发 / .NET编程技术 / ADO.NET Entity Framework深入分析, Part 4

ADO.NET Entity Framework深入分析, Part 42010-09-10EntLibEntity Data Model 是一个概念模型,所有Entity SQL和LINQ to Entities 查询将最终转化为T-SQL的脚本,从数据库中查询数据。这里演示了几种方法来查看生成的T-SQL,有助于Debug或分析问题。

1.使用SQL Server Profiler 工具

与LINQ to SQL比较而言,ObjectContext 类没有提供Log属性或者通用的log机制,因此,无法在Visual Studio 中跟踪所有的T-SQL语句。

如果你想查看所有执行的T-SQL语句,你需要使用SQL Server的Profiler 工具,关于具体如何使用SQL Server Profiler工具,请参考如下文章:

SQL Profiler: Features, functions and setup in SQL Server 2005

http://blog.entlib.com/EntLib/archive/2008/10/27/sql-profiler-features-functions-and-setup-in-sql-server-2005.aspx

2.ToTraceString 方法

另外一种方法去查看生成的T-SQL语句的方法,包括 EntityCommand和ObjectQuery类都有一个ToTraceString() 方法。在一些情况下,可以用来查看内部到底生成什么SQL脚本,而不必一定要使用SQL Server Profiler 工具。需要注意的是:ToTraceString() 方法实际上没有执行查询操作,仅仅是转化查询为SQL脚本。

通过增加一个断点,你可以轻松查看SQL脚本,需要记住的是:事先需要打开数据库连接,否则会抛出InvalidOperationException 异常(Execution of the command requires an open and available connection.The connection’s current state is closed.)

(1)Entity SQL : EntityCommand.ToTraceString() 示例脚本

public IList<Category> GetParentCategory()
{
IList<Category> result = null;
EntityDataReader rdr;
EntityCommand cmd;
string esqlQuery;

using (EntityConnection conn = new EntityConnection("name=AdventureWorksLTEntities"))
{
conn.Open();
esqlQuery = @"Select VALUE c from AdventureWorksLTEntities.Category AS c
Where c.ParentCategory is null ";
result = new List<Category>();

cmd = conn.CreateCommand();
cmd.CommandText = esqlQuery;

Console.WriteLine(cmd.CommandText);
Console.WriteLine(cmd.ToTraceString());

rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

while (rdr.Read())
{
result.Add(this.productGateway.MaterializeCategory(rdr));
}

conn.Close();
}

return result;
}