在EF 4和EF 3.5 SP1中,我们可以使用ToTraceString()方法得到EF查询所生成的SQL。
{
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();
}
}
这里所生成的SQL为:
[Extent1].[ParentID] AS [ParentID],
[Extent1].[Name] AS [Name]
FROM [dbo].[Parent] AS [Extent1]
WHERE N'Lingzhi'=[Extent1].[Name]
在EF 4.1中,我们可以直接调用DbQuery<>的ToString()方法得到所生成的SQL。
{
var people = from p in context.People
where p.PersonID > 100
select p;
string sql = people.ToString();
}
所生成的SQL是:
[Extent1].[PersonID] AS [PersonID],
[Extent1].[Name] AS [Name]
FROM [dbo].[People] AS [Extent1]
WHERE [Extent1].[PersonID] > 100
大 家应该已经猜到,这里的ToString()方法其实也就是调用了ObjectQuery<>的ToTraceString()方法。 DbQuery<>.ToString() ==> System.Data.Entity.Internal.Linq.InternalQuery<>.ToString()方法,此方法 在.NET Reflector得到的实现是这样的:
{
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]