在EF 4和EF 3.5 SP1中,我们可以使用ToTraceString()方法得到EF查询所生成的SQL。
1 using (var context = new TestDBEntities()) 2 { 3 var query = from p in context.Parents 4 where p.Name == "zhaokun" 5 select p; 6 7 ObjectQuery<Parent> parents = query as ObjectQuery<Parent>; 8 if (parents != null) 9 { 10 string sql = parents.ToTraceString(); 11 } 12 }
totracestring
这里所生成的SQL为:
1 [Extent1].[ParentID] AS [ParentID], 2 [Extent1].[Name] AS [Name] 3 FROM [dbo].[Parent] AS [Extent1] 4 WHERE N‘zhaokun‘=[Extent1].[Name]
sqlone
在EF 4.1中,我们可以直接调用DbQuery<>的ToString()方法得到所生成的SQL。
1 using (var context = new MyDbContext()) 2 { 3 var people = from p in context.People 4 where p.PersonID > 100 5 select p; 6 7 string sql = people.ToString(); 8 }
tostring
所生成的SQL是:
1 SELECT 2 [Extent1].[PersonID] AS [PersonID], 3 [Extent1].[Name] AS [Name] 4 FROM [dbo].[People] AS [Extent1] 5 WHERE [Extent1].[PersonID] > 100
sqltwo
这里的ToString()方法其实也就是调用了ObjectQuery<>的ToTraceString()方法。 DbQuery<>.ToString() ==> System.Data.Entity.Internal.Linq.InternalQuery<>.ToString()方法,此方法 在.NET Reflector得到的实现是这样的:
1 public override string ToString() 2 { 3 return this._objectQuery.ToTraceString(); 4 }
tostring()
看书得到!
时间: 2024-10-20 23:32:10