简单记录下,原文在:http://www.dotnetjalps.com/2012/12/Where-I-can-find-SQL-Generated-by-Entity-framework.html

 

1、监测EF产生的SQL

using System;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Data;
 
namespace EntityframeworkSQL
{
    class Program
    {
        static void Main(string[] args)
        {
 
            using (CustomerEntities customerEntities = new CustomerEntities())
            {
                var customerNames = from c in customerEntities.Customers
                             select c.CustomerName;
                string sql = ((System.Data.Objects.ObjectQuery)customerNames).ToTraceString();
 
                Console.WriteLine(sql);
 
            }
             
        }
    }
}

 

2、监测Linq to SQL产生的SQL

using System;
using System.Linq;
using System.Data;
 
namespace LinqToSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            using (CustomerDataContext customerContext = new CustomerDataContext())
            {
                var customerNames = from c in customerContext.Customers
                                    select c.CustomerName;
                string sql = customerContext.GetCommand(customerNames).CommandText;
 
                Console.WriteLine(sql);
            }
        }
    }
}
posted on 2013-01-09 21:47  feichexia  阅读(1959)  评论(0编辑  收藏  举报