question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Incorrect query being produced

See original GitHub issue

The issue

Using the below code, the query is not being produced correctly. Using other EF providers, it produces the correct expected query.

// In this example; order=date; sort=desc
var qEvents = _db.ServerEvents
    .Where(e => e.Server.FarmId == farmId && e.ServerId == serverId)
    .Skip(offset)
    .Take(limit);

switch (order)
{
    case "id":
        if (sort == "asc")
            qEvents = qEvents.OrderBy(e => e.Id);
        else
            qEvents = qEvents.OrderByDescending(e => e.Id);
        break;
    case "user":
        if (sort == "asc")
            qEvents = qEvents.OrderBy(e => e.User.Email);
        else
            qEvents = qEvents.OrderByDescending(e => e.User.Email);
        break;
    case "date":
        if (sort == "asc")
            qEvents = qEvents.OrderBy(e => e.TimeStamp);
        else
            qEvents = qEvents.OrderByDescending(e => e.TimeStamp);
        break;
}

var events = await qEvents.ToArrayAsync(cancellationToken);

Produced Query

SELECT `t`.`id`, `t`.`EventParameter`, `t`.`EventType`, `t`.`ServerId`, `t`.`Reason`, `t`.`Status`, `t`.`TimeStamp`, `t`.`UserId`
FROM (
    SELECT `s`.`id`, `s`.`EventParameter`, `s`.`EventType`, `s`.`ServerId`, `s`.`Reason`, `s`.`Status`, `s`.`TimeStamp`, `s`.`UserId`
    FROM `server_events` AS `s`
    INNER JOIN `servers` AS `s0` ON `s`.`ServerId` = `s0`.`id`
    WHERE (`s0`.`FarmId` = @__farmId_0) AND (`s`.`ServerId` = @__serverId_1)
    LIMIT @__p_3 OFFSET @__p_2
) AS `t`
ORDER BY `t`.`TimeStamp` DESC

Expected Query

SELECT `s`.`id`, `s`.`EventParameter`, `s`.`EventType`, `s`.`ServerId`, `s`.`Reason`, `s`.`Status`, `s`.`TimeStamp`, `s`.`UserId`
FROM `server_events` AS `s`
INNER JOIN `servers` AS `s0` ON `s`.`ServerId` = `s0`.`id`
WHERE (`s0`.`FarmId` = @__farmId_0) AND (`s`.`ServerId` = @__serverId_1)
ORDER BY `s`.`TimeStamp` DESC
LIMIT @__p_2 OFFSET @__p_2

Further technical details

MySQL version: 8.0.23 Operating system: CentOS 8 Pomelo.EntityFrameworkCore.MySql version: 6.0.1

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
lauxjpncommented, Jun 15, 2022

EF and EF Core are two completely different products, that do similar things, but don’t share a codebase. So differences in their translations are not unexpected.

1reaction
lauxjpncommented, Jun 14, 2022

I’ve use the above method of querying/sorting/skipping with other EF providers and they don’t create a sub-query when the methods are called out of order according to the db engine.

@johnwc This appears to be incorrect in my tests. I used the following console project:

Program.cs
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;

namespace IssueConsoleTemplate;

public class ServerEvent
{
    public int Id { get; set; }
    public int EventParameter { get; set; }
    public int EventType { get; set; }
    public int ServerId { get; set; }
    public int Reason { get; set; }
    public int Status { get; set; }
    public int TimeStamp { get; set; }
    public int UserId { get; set; }

    public Server Server { get; set; }
}

public class Server
{
    public int Id { get; set; }
    public int FarmId { get; set; }
}

public class PreserveLastCommandTextInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<DbDataReader> ReaderExecuting(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result)
    {
        ((Context)eventData.Context).LastCommandText = command.CommandText;
        return result;
    }
}

public class Context : DbContext
{
    public DbSet<ServerEvent> ServerEvents { get; set; }
    public DbSet<Server> Servers { get; set; }
    
    public string LastCommandText { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            var connectionString = "server=127.0.0.1;port=3306;user=root;password=;database=Issue1667";
            var serverVersion = ServerVersion.AutoDetect(connectionString);

            optionsBuilder
                //.UseMySql(connectionString, serverVersion)
                //.UseSqlServer(@"Data Source=.\MSSQL15;Integrated Security=SSPI;Initial Catalog=Issue1667")
                //.UseNpgsql(@"server=127.0.0.1;port=5432;user id=postgres;password=postgres;database=Issue1667")
                //.UseSqlite(@"Data Source=Issue1667.db")
                .AddInterceptors(new PreserveLastCommandTextInterceptor())
                .UseLoggerFactory(
                    LoggerFactory.Create(
                        b => b
                            .AddConsole()
                            .AddFilter(level => level >= LogLevel.Information)))
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors();
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}

internal static class Program
{
    private static void Main()
    {
        using var context = new Context();

        context.Database.EnsureDeleted();
        context.Database.EnsureCreated();

        var farmId = 1;
        var serverId = 1;
        var order = "date";
        var sort = "desc";
        var offset = 0;
        var limit = 100;
        
        // In this example; order=date; sort=desc
        var qEvents = context.ServerEvents
            .Where(e => e.Server.FarmId == farmId && e.ServerId == serverId)
            .Skip(offset)
            .Take(limit);

        switch (order)
        {
            // ...
            
            case "date":
                if (sort == "asc")
                    qEvents = qEvents.OrderBy(e => e.TimeStamp);
                else
                    qEvents = qEvents.OrderByDescending(e => e.TimeStamp);
                break;
        }

        qEvents.ToArray();

        Trace.Assert(Regex.IsMatch(context.LastCommandText, @"^select.*?from\s*\(\s*select", RegexOptions.Singleline | RegexOptions.IgnoreCase));
    }
}

All tested providers produce the same nested query (using EF Core 6):

Pomelo (MySQL)
E:/Sources/PomeloIssues/Issue1667/IssueConsoleTemplate/bin/Debug/net6.0/IssueConsoleTemplate.exe 
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.4 initialized 'Context' using provider 'Pomelo.EntityFrameworkCore.MySql:6.0.2-servicing.1' with options: ServerVersion 8.0.25-mysql SensitiveDataLoggingEnabled DetailedErrorsEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (82ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      DROP DATABASE `Issue1667`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (13ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE DATABASE `Issue1667`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (23ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      ALTER DATABASE CHARACTER SET utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (49ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `Servers` (
          `Id` int NOT NULL AUTO_INCREMENT,
          `FarmId` int NOT NULL,
          CONSTRAINT `PK_Servers` PRIMARY KEY (`Id`)
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (67ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `ServerEvents` (
          `Id` int NOT NULL AUTO_INCREMENT,
          `EventParameter` int NOT NULL,
          `EventType` int NOT NULL,
          `ServerId` int NOT NULL,
          `Reason` int NOT NULL,
          `Status` int NOT NULL,
          `TimeStamp` int NOT NULL,
          `UserId` int NOT NULL,
          CONSTRAINT `PK_ServerEvents` PRIMARY KEY (`Id`),
          CONSTRAINT `FK_ServerEvents_Servers_ServerId` FOREIGN KEY (`ServerId`) REFERENCES `Servers` (`Id`) ON DELETE CASCADE
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (55ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE INDEX `IX_ServerEvents_ServerId` ON `ServerEvents` (`ServerId`);
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (31ms) [Parameters=[@__farmId_0='1', @__serverId_1='1', @__p_3='100', @__p_2='0'], CommandType='Text', CommandTimeout='30']
      SELECT `t`.`Id`, `t`.`EventParameter`, `t`.`EventType`, `t`.`Reason`, `t`.`ServerId`, `t`.`Status`, `t`.`TimeStamp`, `t`.`UserId`
      FROM (
          SELECT `s`.`Id`, `s`.`EventParameter`, `s`.`EventType`, `s`.`Reason`, `s`.`ServerId`, `s`.`Status`, `s`.`TimeStamp`, `s`.`UserId`
          FROM `ServerEvents` AS `s`
          INNER JOIN `Servers` AS `s0` ON `s`.`ServerId` = `s0`.`Id`
          WHERE (`s0`.`FarmId` = @__farmId_0) AND (`s`.`ServerId` = @__serverId_1)
          LIMIT @__p_3 OFFSET @__p_2
      ) AS `t`
      ORDER BY `t`.`TimeStamp` DESC
SQL Server
E:/Sources/PomeloIssues/Issue1667/IssueConsoleTemplate/bin/Debug/net6.0/IssueConsoleTemplate.exe 
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.4 initialized 'Context' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.2' with options: SensitiveDataLoggingEnabled DetailedErrorsEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (34ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT 1
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
      IF SERVERPROPERTY('EngineEdition') <> 5
      BEGIN
          ALTER DATABASE [Issue1667] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
      END;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (32ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
      DROP DATABASE [Issue1667];
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (265ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
      CREATE DATABASE [Issue1667];
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (86ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
      IF SERVERPROPERTY('EngineEdition') <> 5
      BEGIN
          ALTER DATABASE [Issue1667] SET READ_COMMITTED_SNAPSHOT ON;
      END;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT 1
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE [Servers] (
          [Id] int NOT NULL IDENTITY,
          [FarmId] int NOT NULL,
          CONSTRAINT [PK_Servers] PRIMARY KEY ([Id])
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE [ServerEvents] (
          [Id] int NOT NULL IDENTITY,
          [EventParameter] int NOT NULL,
          [EventType] int NOT NULL,
          [ServerId] int NOT NULL,
          [Reason] int NOT NULL,
          [Status] int NOT NULL,
          [TimeStamp] int NOT NULL,
          [UserId] int NOT NULL,
          CONSTRAINT [PK_ServerEvents] PRIMARY KEY ([Id]),
          CONSTRAINT [FK_ServerEvents_Servers_ServerId] FOREIGN KEY ([ServerId]) REFERENCES [Servers] ([Id]) ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE INDEX [IX_ServerEvents_ServerId] ON [ServerEvents] ([ServerId]);
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (23ms) [Parameters=[@__farmId_0='1', @__serverId_1='1', @__p_2='0', @__p_3='100'], CommandType='Text', CommandTimeout='30']
      SELECT [t].[Id], [t].[EventParameter], [t].[EventType], [t].[Reason], [t].[ServerId], [t].[Status], [t].[TimeStamp], [t].[UserId]
      FROM (
          SELECT [s].[Id], [s].[EventParameter], [s].[EventType], [s].[Reason], [s].[ServerId], [s].[Status], [s].[TimeStamp], [s].[UserId]
          FROM [ServerEvents] AS [s]
          INNER JOIN [Servers] AS [s0] ON [s].[ServerId] = [s0].[Id]
          WHERE ([s0].[FarmId] = @__farmId_0) AND ([s].[ServerId] = @__serverId_1)
          ORDER BY (SELECT 1)
          OFFSET @__p_2 ROWS FETCH NEXT @__p_3 ROWS ONLY
      ) AS [t]
      ORDER BY [t].[TimeStamp] DESC
Npgsql (PostgreSQL)
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.4 initialized 'Context' using provider 'Npgsql.EntityFrameworkCore.PostgreSQL:6.0.4+6cb649128e3e7aa8eddd77dfa75b34bad51e6e94' with options: SensitiveDataLoggingEnabled DetailedErrorsEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (86ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      REVOKE CONNECT ON DATABASE "Issue1667" FROM PUBLIC;
      SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname = 'Issue1667';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (168ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      DROP DATABASE "Issue1667";
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1,221ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE DATABASE "Issue1667";
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (20ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE "Servers" (
          "Id" integer GENERATED BY DEFAULT AS IDENTITY,
          "FarmId" integer NOT NULL,
          CONSTRAINT "PK_Servers" PRIMARY KEY ("Id")
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (10ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE "ServerEvents" (
          "Id" integer GENERATED BY DEFAULT AS IDENTITY,
          "EventParameter" integer NOT NULL,
          "EventType" integer NOT NULL,
          "ServerId" integer NOT NULL,
          "Reason" integer NOT NULL,
          "Status" integer NOT NULL,
          "TimeStamp" integer NOT NULL,
          "UserId" integer NOT NULL,
          CONSTRAINT "PK_ServerEvents" PRIMARY KEY ("Id"),
          CONSTRAINT "FK_ServerEvents_Servers_ServerId" FOREIGN KEY ("ServerId") REFERENCES "Servers" ("Id") ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE INDEX "IX_ServerEvents_ServerId" ON "ServerEvents" ("ServerId");
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (14ms) [Parameters=[@__farmId_0='1', @__serverId_1='1', @__p_3='100', @__p_2='0'], CommandType='Text', CommandTimeout='30']
      SELECT t."Id", t."EventParameter", t."EventType", t."Reason", t."ServerId", t."Status", t."TimeStamp", t."UserId"
      FROM (
          SELECT s."Id", s."EventParameter", s."EventType", s."Reason", s."ServerId", s."Status", s."TimeStamp", s."UserId"
          FROM "ServerEvents" AS s
          INNER JOIN "Servers" AS s0 ON s."ServerId" = s0."Id"
          WHERE (s0."FarmId" = @__farmId_0) AND (s."ServerId" = @__serverId_1)
          LIMIT @__p_3 OFFSET @__p_2
      ) AS t
      ORDER BY t."TimeStamp" DESC
Sqlite
E:/Sources/PomeloIssues/Issue1667/IssueConsoleTemplate/bin/Debug/net6.0/IssueConsoleTemplate.exe 
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.4 initialized 'Context' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.2' with options: SensitiveDataLoggingEnabled DetailedErrorsEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (30ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      PRAGMA journal_mode = 'wal';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE "Servers" (
          "Id" INTEGER NOT NULL CONSTRAINT "PK_Servers" PRIMARY KEY AUTOINCREMENT,
          "FarmId" INTEGER NOT NULL
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE "ServerEvents" (
          "Id" INTEGER NOT NULL CONSTRAINT "PK_ServerEvents" PRIMARY KEY AUTOINCREMENT,
          "EventParameter" INTEGER NOT NULL,
          "EventType" INTEGER NOT NULL,
          "ServerId" INTEGER NOT NULL,
          "Reason" INTEGER NOT NULL,
          "Status" INTEGER NOT NULL,
          "TimeStamp" INTEGER NOT NULL,
          "UserId" INTEGER NOT NULL,
          CONSTRAINT "FK_ServerEvents_Servers_ServerId" FOREIGN KEY ("ServerId") REFERENCES "Servers" ("Id") ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE INDEX "IX_ServerEvents_ServerId" ON "ServerEvents" ("ServerId");
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (32,637ms) [Parameters=[@__farmId_0='1', @__serverId_1='1', @__p_3='100', @__p_2='0'], CommandType='Text', CommandTimeout='30']
      SELECT "t"."Id", "t"."EventParameter", "t"."EventType", "t"."Reason", "t"."ServerId", "t"."Status", "t"."TimeStamp", "t"."UserId"
      FROM (
          SELECT "s"."Id", "s"."EventParameter", "s"."EventType", "s"."Reason", "s"."ServerId", "s"."Status", "s"."TimeStamp", "s"."UserId"
          FROM "ServerEvents" AS "s"
          INNER JOIN "Servers" AS "s0" ON "s"."ServerId" = "s0"."Id"
          WHERE ("s0"."FarmId" = @__farmId_0) AND ("s"."ServerId" = @__serverId_1)
          LIMIT @__p_3 OFFSET @__p_2
      ) AS "t"
      ORDER BY "t"."TimeStamp" DESC

That is correct within MySql, but it should be irrelevant within EF. The order of method calls for the same query object should just “configure” EF to know what should be ordered, filtered, selected, etc…; not force it to create sub-queries.

The SQL statements and clauses should reflect your LINQ query as much as possible, so that you get an expected result.

In your case, since you first call Skip(), then Take() and finally OrderByDescending(), the only way to accurately reflect this is to create a sub query, which EF Core does for all providers.

It also outputs a warning, as you can see in all console outputs above:

warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering
would otherwise get erased.

So: order first, then skip and take.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Query producing incorrect results - python
Query producing incorrect results ... I realize that there is a chance it will try to sort the same table twice, but the...
Read more >
Incorrect query result - SQL Server 2016
I'm seeing incorrect result returned by a query I just ran this morning in production (I ran the same query last night couple...
Read more >
Top 5 Reasons for Wrong Results in SQL Server
Many people have come across situations where their queries are returning incorrect results - sometimes this is due to a bug in SQL...
Read more >
Incorrect query results for execution plan, unsure of exact ...
I'm not familiar with a way to view execution plan in production and running the query in sql studio didn't result in same...
Read more >
SQL query and folding produces incorrect results
Solved: I have a query that like this: let //Variables - Business Unit: BusinessUnitFilterList = Text.Split(#"Business Unit Filter",
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found