如何使用 Where 子句从 Linq 查询中跟踪 SQL 语句?

How to trace SQL statement from Linq query with Where clause?

我有 Linq 语句:

context.Files.Where(f => ids.Contains(f.FileId))

我正在尝试 trace it with Extended Events,但我没有在输出中看到此查询。如果我将鼠标悬停在 Files 上然后打开 Results View,我会看到发出以下命令:

SELECT [t0].[FileId], [t0].[Type], [t0].[Name], ... 
FROM [dbo].[File] AS [to]

基本上,我需要查明查询是否优化,我需要硬性证明。

由于 Deferred execution,您的查询本身不会产生任何 SQL。

但是,如果您在调试器中并且有这样的语句

var query = context.Files.Where(f => ids.Contains(f.FileId))

然后

query.ToList();

将执行您的查询,因此您应该在 Sql Profiler 等中看到生成的 SQL

或者

Query.ToString();

不会执行查询,但会return生成SQL语句(但不显示涉及的参数值)。