独上高楼网站
  •    你所在位置:首页 VS.netASP.netADO.net〉ADO.NET Entity Framework 深入分析-Part 4
  • ADO.NET Entity Framework 深入分析-Part 4
  • 作者:EntLib  文章来源:blog.EntLib.com  发布日期:2008-11-03  浏览次数:243
  • 打印这篇文章
  • ADO.NET Entity Framework 深入分析, Part 4 (提供示例程序下载)
     
     
    前面的Part 1-3的文章,介绍了Entity Data Model、Entity SQL、ObjectQuery、EntityCommand、LINQ to Entities等等及其代码演示。这篇文章主要演示如何通过相关技术或Debug工具,如SQL Server Profiler、ToTraceString 方法、eSqlBlast 工具、LINQPad工具等等,来查看生成的T-SQL脚本。
    Entity 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
     
    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;
            }
     
    示例界面如下:


     
    (2)Entity SQL : ObjectQuery.ToTraceString() 示例脚本如下:
    NorthwindEntities context = new NorthwindEntities();
     
    var sql = "SELECT VALUE emp FROM NorthwindEntities.Employees AS emp " +
              "WHERE emp.Country = @country";
    var query = context.CreateQuery(sql);
    query.Parameters.Add(new ObjectParameter("country", "USA"));
     
    if (context.Connection.State != ConnectionState.Open)
     context.Connection.Open();
     
    Console.WriteLine(query.ToTraceString());
     
    (3)LINQ to Entities : (query as ObjectQuery).ToTraceString() 示例脚本
    需要使用类型转换,将LINQ to Entities (IQueryable) 查询转化为ObjectQuery,这样就可以调用ToTraceString() 方法了。
    NorthwindEntities context = new NorthwindEntities();
     
    string country = "USA";
    var query = from e in context.Employees
                where e.Country == country
                select e;
     
    if (context.Connection.State != ConnectionState.Open)
     context.Connection.Open();
    Console.WriteLine((query as ObjectQuery).ToTraceString());
     
    也可以通过反射(Reflection)和Invoke() 方法,得到相同的结果:
    Console.WriteLine(query.GetType().GetMethod("ToTraceString").Invoke(query, null));
     
    3. 使用eSqlBlast 工具
    微软也提供了一个免费的工具来帮助学习Entity SQL。
    eSqlBlast 的下载地址(含有源代码,需要自己编译一下)及其相关介绍(eSqlBlast for VS 2008 SP1):
    如果懒得编译,可以直接在本文章底部点击下载链接,下载已经编译好的可执行文件。
     
    运行界面如下:

     
    Connection 页面用来指定3个元数据文件(CSDL/SSDL/MSL)和数据库连接字符串。数据库连接字符串可以直接从App.config 复制过来。点击Connect 按钮进行连接。
     
    Model 页面用来显示所有的EntitySets和EntityTypes。

     
    Query 页面可以输入 Entity SQL脚本,你会注意到eSqlBlast 支持智能提示(IntelliSense),酷吧!!!目前,Visual Studio 2008 sp1 尚不支持Entity SQL 的职能提示呢。

     
    点击Execute 执行按钮,执行结果将以HTML的格式显示在Results 页面,如下图所示。包括4个部分:Enttiy Command (也就是CommandText 属性值)、Store Command(生成的T-SQL脚本,也就是ToTraceString() 方法产生的脚本)、Record Count(结果集的记录数)、Data(实际记录结果)。
     


     
    4. 使用免费LINQPad 工具
    LINQPad 是一个优秀的LINQ 表达式测试工具,原本设计用来执行LINQ to Objects 和LINQ to SQL查询,但是也可以用来执行LINQ to Entities 查询。
     
    如下图所示,执行LINQ to SQL查询,并调用扩展方法Dump() 输出结果。
     
     
    LINQPad 免费工具可以到如下地址下载:
     
    EntLib.com Blog (http://blog.EntLib.com ) 开源博客小组编写,欢迎加入我们的开源团队。

     

     点击下载 示例程序 AdventureWorks_EntityFrameworkDemo_v2 (356 KB)

  • 打印这篇文章
  • 与本文主题相关的文章
  • 返回首页