EF Core issue 39059 - Negated nullable comparison in a conditional returns wrong results

CSharp · Console

/Program.cs

using Microsoft.EntityFrameworkCore;
using System.Collections.Immutable;
using System.Linq;
using System;
using System.Linq.Expressions;

using var context = new MyDbContext();

await context.Database.EnsureCreatedAsync();

Expression<Func<TestRow, int?>> expr = e => !(e.Col1 <= 1) ? 0 : 1;

// Through EF Core
foreach (var db in (await context.TestRows.Select(expr).ToListAsync()))
{
    Console.WriteLine(db);
}

Console.WriteLine("--------------");

// Through LINQ
foreach (var db in TestRow.CreateTestRows().Select(expr.Compile()))
{
	Console.WriteLine(db);
}

public class MyDbContext : DbContext
{
    public DbSet<TestRow> TestRows => Set<TestRow>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestRow>().Property(x => x.Id).ValueGeneratedNever();
        modelBuilder.Entity<TestRow>().HasData(TestRow.CreateTestRows());
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseSqlServer(FiddleHelper.GetConnectionStringSqlServer())/*.LogTo(Console.WriteLine)*/;
}

public record TestRow(int Id, int? Col1)
{
    public static ImmutableArray<TestRow> CreateTestRows() => [new(2, null)];
}
;