IQueryable 的顺序是否保留在 C# EF Core 中的实际查询中?

Roy*_*ris 2 c# linq iqueryable entity-framework-core

因此,当我为 DbContext 编写查询时,可查询的顺序实际上代表了输出查询。例如:

_dbContext
.Table
.OrderBy(i => i.Date)
.Take(25)
.Where(i => i.Variable == "something")
.ToList()
Run Code Online (Sandbox Code Playgroud)

相对

_dbContext
.Table
.Where(i => i.Variable == "something")
.OrderBy(i => i.Date)
.Take(25)
.ToList()
Run Code Online (Sandbox Code Playgroud)

因此,这些查询是不同的,因为第一个查询按日期获取最后 25 个项目并执行 where 子句。但另一个从where的结果中取出25。

当它被执行时,它会保持这个顺序吗?或者这就像一个构建器,其中所有属性都被设置和执行。如果我查看普通的 SQL,我无法在同一查询中的TAKE之前进行操作。WHERE所以对我来说这是有道理的。


我感到困惑的原因是,如果我用 MS SQL 编写第一个查询,我们会得到以下结果:

SELECT TOP 25 * FROM `Table` WHERE `Variable` = 'something' ORDER BY `Date`
Run Code Online (Sandbox Code Playgroud)

其中从 where 结果中取出 25。

pwr*_*imo 5

如果启用记录 SQL,您将看到这两个查询的顺序很重要

 SELECT [t].[Id], [t].[Date], [t].[Variable]
  FROM (
      SELECT TOP(@__p_0) [m].[Id], [m].[Date], [m].[Variable]
      FROM [MyObjects] AS [m]
      ORDER BY [m].[Date]
  ) AS [t]
  WHERE [t].[Variable] = N'something'
  ORDER BY [t].[Date]
Run Code Online (Sandbox Code Playgroud)

SELECT TOP(@__p_0) [m].[Id], [m].[Date], [m].[Variable]
      FROM [MyObjects] AS [m]
      WHERE [m].[Variable] = N'something'
      ORDER BY [m].[Date]
Run Code Online (Sandbox Code Playgroud)

可以通过在 appsettings.json 中设置 EntityFramework Core 的日志级别来启用日志记录

{
  "Logging": {
    "LogLevel": {
      "Microsoft.EntityFrameworkCore": "Debug"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

您还需要确保您的数据库上下文具有此特定的构造函数重载

public AppDbContext(DbContextOptions options) : base(options)
{
}
Run Code Online (Sandbox Code Playgroud)