Skip to content

Invalid translation for constant negative TimeSpan for SQL Server #39222

Closed

Description

@Aziz-Dhiab

Bug description

When the query contains a constant negative TimeSpan, the translated SQL does not contain the negative sign.
This is probably because SQL Server time column cannot contain negative values.
This will result in the query executing without error and returning a wrong result.
This happens only for constants as parameters will cause an OverflowException.

Your code

context.Set<BasicTypesEntity>()
    .Where(b => b.TimeSpan > TimeSpan.FromHours(-1))
    .ToList()
SELECT [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE [b].[TimeSpan] > '01:00:00'

Stack traces


Verbose output


EF Core version

main 2b99285

Database provider

Microsoft.EntityFrameworkCore.SqlServer

Target framework

No response

Operating system

No response

IDE

No response

Activity

  1. added this to the Backlog milestone on Oct 12, 2026
  2. added theissue type on Oct 12, 2026
  3. Saad-elnagar commented on Oct 13, 2026

    @Saad-elnagar
    Contributor

    I looked into this. The constant is generated by SqlServerTimeSpanTypeMapping.GenerateNonNullSqlLiteral, which uses '{0:hh\:mm\:ss}' (and the F variants). That custom format only prints the hours component, so the negative sign is lost (TimeSpan.FromHours(-1) becomes '01:00:00'). It likely drops the days component for values >= 24h as well, though I haven't verified that.

    Since the time type can't represent negative values or values >= 24h, and parameters already throw an OverflowException, I'd suggest making the literal path consistent: throw a clear exception from GenerateNonNullSqlLiteral when the value is outside [0, 24h), instead of silently generating a wrong literal. I'd add cases for this in SqlServerTypeMappingTest.

    Would the team be OK with that behavior, or would you prefer a different approach (e.g. translating such comparisons differently)? I'm happy to work on a PR if this is available.

  4. AndriySvyryd commented on Oct 21, 2026

    @AndriySvyryd
    Member

    @Saad-elnagar Sounds good

  5. added a commit that references this issue on Oct 22, 2026
    38b28f5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions