Skip to content

SqlServer: Translate TimeSpan members #19632

Description

@aleksandar-manukov

Hi,

At work, we use a query which uses TimeSpan members Hours, Minutes and Seconds, but EFCore doesn't translate these members to sql.

We fix the problem creating SqlServerTimeSpanMemberTranslator like the SqlServerDateTimeMemberTranslator and we override the SqlServerMemberTranslatorProvider to include also our SqlServerTimeSpanMemberTranslator.

I think SqlServerTimeSpanMemberTranslator can be useful also to other .NET developers, so if you want I can make a PR to include it to EFCore.SqlServer project.

Activity

  1. ajcvickers commented on Jan 21, 2020

    @ajcvickers
    Contributor

    @aleksandar-manukov Yes, we would be interested in a PR for this. We're curious how it deals with time spans that cover more than 24 hours, where the naive mapping to T-SQL time doesn't work.

  2. aleksandar-manukov commented on Jan 22, 2020

    @aleksandar-manukov
    ContributorAuthor

    Hi @ajcvickers

    Never needed to deal with TimeSpan which is more than 24 hours. Our use case is that we have a time column for execution schedules and we need to compare it to current hours and minutes and to compare its time parts to other datetime column time parts which is holding execution schedules history. So we use the following query

    // This is selecting all schedulers with scheduled time equal or bigger to the current time (hours and minutes) and for which there is no record in the StepScheduleHistory for today with time bigger than the scheduled.
    return await _dbContext.StepSchedules
        .Where(ss => ss.StepId == stepId &&
            (ss.ScheduledTime.Hours > DateTime.Now.Hour ||
                (ss.ScheduledTime.Hours == DateTime.Now.Hour &&
                    ss.ScheduledTime.Minutes >= DateTime.Now.Minute)) &&
            !_dbContext.StepScheduleHistories
                .Any(ssh => ssh.StepScheduleId == ss.Id &&
                    ssh.ExecutionDate.Day == DateTime.Today.Day &&
                    ssh.ExecutionDate.Month == DateTime.Today.Month &&
                    ssh.ExecutionDate.Year == DateTime.Today.Year &&
                    (ssh.ExecutionDate.Hour > ss.ScheduledTime.Hours ||
                        (ssh.ExecutionDate.Hour == ss.ScheduledTime.Hours &&
                            (ssh.ExecutionDate.Minute > ss.ScheduledTime.Minutes ||
                                (ssh.ExecutionDate.Minute == ss.ScheduledTime.Minutes &&
                                    ssh.ExecutionDate.Second >= ss.ScheduledTime.Seconds))))))
        .MapTo<StepScheduleViewModel>()
        .OrderBy(ss => ss.ScheduledTime)
        .ToListAsync();
    

    This query works with EntityFramework 6 but in EntityFramework Core ss.ScheduledTime.Hours, ss.ScheduledTime.Minutes and ss.ScheduledTime.Seconds cannot be translated to SQL. That's why we make SqlServerTimeSpanMemberTranslator like the SqlServerDateTimeMemberTranslator which is translating for example ss.ScheduledTime.Hours to datepart(hour, [ScheduledTime]).

    Do you want me to make a PR and to continue discussion there or you need something more advanced to handle TimeSpan members translation?

  3. ajcvickers commented on Jan 22, 2020

    @ajcvickers
    Contributor

    @aleksandar-manukov Thanks for the additional info. We will discuss.

  4. bricelam commented on Jan 24, 2020

    @bricelam
    Contributor
    .NET Transact-SQL
    timeSpan.Hours DATEPART(hour, @TimeSpan)
    timeSpan.Minutes DATEPART(minute, @TimeSpan)
    timeSpan.Seconds DATEPART(second, @TimeSpan)
    timeSpan.Milliseconds DATEPART(millisecond, @TimeSpan)
  5. bricelam commented on Jan 24, 2020

    @bricelam
    Contributor

    The DATEDIFF and DATEADD functions don't really have .NET equivalents.

  6. aleksandar-manukov commented on Jan 24, 2020

    @aleksandar-manukov
    ContributorAuthor

    Hi @bricelam

    I have never meant to translate TimeSpan members with datediff and dateadd functions. What we use (as you can see in my previous comment) is to translate TimeSpan.Hours -> datepart(hour, @TimeSpan) which is currently missing in EF Core. If you want I can make a PR to add SqlServerTimeSpanMemberTranslator to translate TimeSpan members to appropriate datepart function.

  7. bricelam commented on Jan 24, 2020

    @bricelam
    Contributor

    A PR would be awesome!

    I have never meant to translate TimeSpan members with datediff and dateadd functions.

    Oh I was just doing my due diligence to see what other members we could translate. I only found Milliseconds.

  8. bricelam commented on Jan 24, 2020

    @bricelam
    Contributor

    (You may have already seen it, but I have work-in-progress PR out for TimeSpan translations on SQLite)

  9. bricelam commented on Jan 24, 2020

    @bricelam
    Contributor

    @cowmanjoe What SQL were you proposing for the Total* members in PR #19643?

  10. aleksandar-manukov commented on Jan 25, 2020

    @aleksandar-manukov
    ContributorAuthor

    @bricelam thanks. I will check your PR especially to see what tests I need to do and I will try to make a PR soon.

  11. cowmanjoe commented on Jan 27, 2020

    @cowmanjoe

    @bricelam, initially tried to do a datediff (this works with time sql value), but I don't think this is possible to do with better precision than milliseconds. I ended up using datepart to get each component separately, then multiplying those values by the correct ratio to get the total nanoseconds. Then I would divide that value by the appropriate ratio for the time units requested. This ended up being quite a big piece of SQL, but I don't think it would be that slow since it is essentially just extracting a few values from the time data and then multiplying and dividing a constant amount of times.

  12. added this to the Backlog milestone on Jan 28, 2020
  13. added a commit that references this issue on Feb 19, 2020
  14. 7 remaining items

  15. bricelam commented on Jan 12, 2023

    @bricelam
    Contributor

    @SoftCircuits You have to write it like this for now: g.Average(t => EF.Functions.DateDiffMinute(t.Departure!.Value, t.Arrival))

  16. removed their assignment
    on Jul 8, 2023
  17. added theissue type on Jun 15, 2025
  18. roji commented on Oct 9, 2025

    @roji
    Member

    Note: also translate the Total* members.

  19. Xriuk commented on Oct 9, 2025

    @Xriuk

    @SoftCircuits You have to write it like this for now: g.Average(t => EF.Functions.DateDiffMinute(t.Departure!.Value, t.Arrival))

    These translations for Total* properties could already be created, and it would work for TimeSpans bigger than 24h because the difference between dates returns a TimeSpan but accessing any member of the returned TimeSpan returns an integer.
    But it would be a partial translation, only suitable for diffences of DateTimes and DateTimeOffsets.
    Also the two arguments for EF.Functions.DateDiff* functions need to be swapped because the sign returned is inverted.

  20. Laurianti commented on Oct 31, 2026

    @Laurianti
    Contributor

    I'd like to take the Total* members (TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds) on SQL Server, computed from DATEPART over the time value so it works on all supported versions, with tests in the TimeSpan translation suites. I'll open a PR so it can be reviewed.

  21. Xriuk commented on Oct 31, 2026

    @Xriuk

    31. I'd like to take the Total* members (TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds) on SQL Server, computed from DATEPART over the time value so it works on all supported versions, with tests in the TimeSpan translation suites. I'll open a PR so it can be reviewed.

    I'm not sure but I think that Total* members might not be suitable for DATEPART, even with time. Because for time 12:30 hours part is 12 while TotalHours would be 12.5

  22. Laurianti commented on Oct 31, 2026

    @Laurianti
    Contributor

    Right, a single DATEPART isn't enough. The idea is to add up all the parts into the exact number of ticks (hour * 3600 + minute * 60 + second, plus the fraction from DATEPART(nanosecond)) and divide once, as .NET does, so 12:30 gives 12.5 for TotalHours.

  23. added a commit that references this issue on Nov 4, 2026
    e3323b4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions