添加 引用:
using System.Data.Objects;

var results = db.tb_product.Where(s => s.ID == 2160);
var sql = (results as ObjectQuery<tb_product>).ToTraceString();


另一种方法:
using (var context = new TestDBEntities())
{
    var query = from p in context.Parents
                where p.Name == "Lingzhi"
                select p;

    ObjectQuery<Parent> parents = query as ObjectQuery<Parent>;
    if (parents != null)
    {
        string sql = parents.ToTraceString();
    }
}

在EF4.1中,可以直接 使用 ToString() 
using (var context = new MyDbContext())
{
    var people = from p in context.People
                 where p.PersonID > 100
                 select p;

    string sql = people.ToString();
}

大 家应该已经猜到,这里的ToString()方法其实也就是调用了ObjectQuery<>的ToTraceString()方法。 DbQuery<>.ToString() ==> System.Data.Entity.Internal.Linq.InternalQuery<>.ToString()方法,此方法 在.NET Reflector得到的实现是这样的:

public override string ToString()
{
    
return this._objectQuery.ToTraceString();
}



查ef生成sql的例子

  [TestFixture]

    public class TestEFModel

    {

        [Test]

        public void Select()

        {

            using (var edm = new NorthwindEntities())

            {

                //基于表达式的查询语法

                ObjectQuery<Customers> customers = edm.Customers;

                IQueryable<Customers> cust1 = from c in customers

                                              select c;

                Assert.Greater(cust1.Count(), 0);

                //使用ObjectQuery类的ToTraceString()方法显示查询SQL语句

                Console.WriteLine(customers.ToTraceString());

 

 

            }

        }

    }

}

输出:

SELECT

[Extent1].[CustomerID] AS [CustomerID],

[Extent1].[CompanyName] AS [CompanyName],

[Extent1].[ContactName] AS [ContactName],

[Extent1].[ContactTitle] AS [ContactTitle],

[Extent1].[Address] AS [Address],

[Extent1].[City] AS [City],

[Extent1].[Region] AS [Region],

[Extent1].[PostalCode] AS [PostalCode],

[Extent1].[Country] AS [Country],

[Extent1].[Phone] AS [Phone],

[Extent1].[Fax] AS [Fax]

FROM [dbo].[Customers] AS [Extent1]



本文转载:CSDN博客