How do I store a negative TimeSpan in Entity Framework?

David Thielen 3,036 Reputation points
2024-06-02T02:42:02.63+00:00

Hi all;

I store shifts to events with a TimeSpan as the offset from the start of the event and another TimeSpan as the duration of the shift. The setup shift starts before the event (so everyone see the event as 11:00am - 4:00pm as desired while the setup shift starts at 10:15am).

Entity Framework throws an exception saving a TimeSpan < 0 or >= 24:00:00. Is there a way to save a TimeSpan outside the 0 .. 24 hour range?

thanks - dave

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
736 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 64,566 Reputation points
    2024-06-02T16:13:54.5433333+00:00

    Your issue is the default mapping of TimeSpan is to sql Time, which is a time, not a time period. But EF supports mapping a TimeSpan to a long, and will convert the TimeSpan to ticks, which is a period and can be negative.

    https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.