Skip to content

Null check is wrongly dropped for NodaTime.Interval.Start and NodaTime.Interval.End with efcore linq2sql #3585

Closed

Description

@AsgerPetersen

Reproducer: https://github.com/AsgerPetersen/npgsql_nodatime_interval

With these classes

public class Event
{
    public int Id { get; set; }
    public Interval Duration { get; set; }
}

this query will return the wrong result

var queryTime = Instant.FromDateTimeUtc(DateTime.UtcNow);
var query = context.Events
            .Select(e => new{e.Id, e.Duration.Start, e.Duration.End})
            .Where(p => p.Start <= queryTime && (p.End == null || p.End > queryTime));

The expression e.Duration.End == null is wrongly assumed to be always false because Interval.End is non nullable and it is dropped from the resulting SQL:

-- @__queryTime_0='2025-07-25T13:27:08Z' (DbType = DateTime)
SELECT e."Id", lower(e."Duration") AS "Start", upper(e."Duration") AS "End"
FROM "Events" AS e
WHERE lower(e."Duration") <= @__queryTime_0 AND upper(e."Duration") > @__queryTime_0

The problem is that p.End actually IS null.

This is pretty tricky since this also happens when you explicitly project to Instant? like in the reproducer.

A workaround to let npgsql know that the Instant actually may be null is this:

query = context.Events
            .Select(e => new { Id = e.Id, Start = e.Duration.Start, End = e.Duration.HasEnd ? e.Duration.End : null })
            .Where(p => p.Start <= queryTime && (p.End == null || p.End.Value > queryTime));

The workaround produces a less readable SQL, but it works.

Activity

  1. added theissue type on Oct 17, 2026
  2. roji commented on Oct 17, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed bug in the Npgsql NodaTime range-bound translation. With a non-null Duration whose upper bound is unbounded, the reported query returns 0 rows instead of 1. Explicitly projecting End as Instant? does not prevent this. I also reproduced the equivalent problem for an unbounded Start.

    The query can be reduced to:

    context.Events
        .Select(e => new { End = (Instant?)e.Duration.End })
        .Where(p => p.End == null)

    On the reported Npgsql 9.0.4 / EF Core 9.0.7 combination, this generates:

    SELECT upper(e."Duration")::timestamptz AS "End"
    FROM "Events" AS e
    WHERE FALSE

    The predicate should instead retain upper(e."Duration") IS NULL: PostgreSQL's upper() returns null for an unbounded upper bound even when the range itself is not null.

    Version comparison: the reduced query returned 0 instead of 1 in each of these combinations, using PostgreSQL 18.4:

    Npgsql provider and NodaTime plugin EF Core / Relational
    8.0.0 8.0.0
    9.0.3 9.0.7
    9.0.4 9.0.7
    10.0.3 10.0.4
    11.0.0-rc.1.1 11.0.0-rc.1.26425.128

    This is not newly introduced in 9.0.4 or EF Core 9; it is already present in 8.0.0. No previously working version was identified. It remains reproducible in the latest stable and prerelease NodaTime packages available when checked.

    Likely cause: both Lower() and Upper() in NpgsqlNodaTimeMemberTranslator.TranslateInterval specify nullable: true but also argumentsPropagateNullability: TrueArrays[1]. That propagation metadata permits EF to replace a bound's null check with a null check on the range argument. Since Duration is required, that becomes false. These functions can also return null for a non-null range, so their argument-propagation entries should be false while retaining nullable: true.

    The reported HasEnd ? End : null workaround was also checked and returned the expected row.

    Provider scope and related issues: this points to Npgsql's PostgreSQL-specific range translation, rather than a general EF Core bug. A direct SQLite comparison stops at model validation because SQLite does not support the Interval mapping. No exact duplicate was found in the EF Core or Npgsql issue searches. Related background: dotnet/efcore#23042 explains why functions that can return null with non-null arguments must not opt into this null-propagation optimization; it is not a duplicate report of this NodaTime bug.

    minimal repro

    This translation-only repro needs no database or seed data. The wrong-result behavior above was separately confirmed by executing against a database containing one event with new Interval(Instant.FromUtc(2025, 1, 1, 0, 0), null).

    Use a net8.0 console project with these package references:

    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.7" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="9.0.4" />
    using System;
    using System.Linq;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    using NodaTime;
    
    await using var context = new AppDbContext();
    Console.WriteLine(context.Events
        .Select(e => new { End = (Instant?)e.Duration.End })
        .Where(p => p.End == null)
        .ToQueryString());
    
    public class AppDbContext : DbContext
    {
        public DbSet<Event> Events { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(
                    Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"),
                    o => o.UseNodaTime())
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    public class Event
    {
        public int Id { get; set; }
        public Interval Duration { get; set; }
    }
  3. self-assigned this
    on Oct 17, 2026
  4. added this to the 10.0.4 milestone on Oct 17, 2026
  5. added a commit that references this issue on Oct 18, 2026
    affe681
  6. added a commit that references this issue on Oct 18, 2026
    371b3d5
  7. added a commit that references this issue on Oct 18, 2026
    5a8f68a
  8. changed the title [-]null check is wrongly dropped for NodaTime.Interval.Start and NodaTime.Interval.End with efcore linq2sql[/-] [+]Null check is wrongly dropped for NodaTime.Interval.Start and NodaTime.Interval.End with efcore linq2sql[/+] on Oct 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions