EF查询生成的SQL

在EF 4和EF 3.5 SP1中,我们可以使用ToTraceString()方法得到EF查询所生成的SQL。

 using (var context = new TestDBEntities())
{
var query = from p in context.Parents
where p.Name == "zhaokun"
select p; ObjectQuery<Parent> parents = query as ObjectQuery<Parent>;
if (parents != null)
{
string sql = parents.ToTraceString();
}
}

totracestring

这里所生成的SQL为:

 [Extent1].[ParentID] AS [ParentID],
[Extent1].[Name] AS [Name]
FROM [dbo].[Parent] AS [Extent1]
WHERE N'zhaokun'=[Extent1].[Name]

sqlone

在EF 4.1中,我们可以直接调用DbQuery<>的ToString()方法得到所生成的SQL。

 using (var context = new MyDbContext())
{
var people = from p in context.People
where p.PersonID >
select p; string sql = people.ToString();
}

tostring

所生成的SQL是:

 SELECT
[Extent1].[PersonID] AS [PersonID],
[Extent1].[Name] AS [Name]
FROM [dbo].[People] AS [Extent1]
WHERE [Extent1].[PersonID] >

sqltwo

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

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

tostring()

看书得到!

上一篇:EF查询视图只得到一条记录


下一篇:在RHEL5.4下安装ORACLE11G