Storing TimeSpan with Entity Framework Codefirst - SqlDbType.Time overflow

后端 未结 4 791
攒了一身酷
攒了一身酷 2021-02-05 02:41

I\'m trying to seed some constants into my DB:

context.Stages.AddOrUpdate(s => s.Name,
                                   new Stage()
                                


        
4条回答
  •  余生分开走
    2021-02-05 03:13

    The problem, as previously mentioned, is the fact that EF maps the TimeSpan class to Time, which is limited to 24 hours.

    If you need to store a timespan of greater than 24 hours, I would suggest one of the following two approaches:

    1) Create a TimeSpan entity with int properties for the different elements of a timespan, something like:

     public class Timespan
    {
        public Int64 Id { get; set; }
    
        public Int16 Years { get; set; }
    
        public int Months { get; set; }
    
        public Int64 Days { get; set; }
    
        public Int64 Hours { get; set; }
    
        public Int64 Minutes { get; set; }
    }
    

    Simply add a foreign reference in the applicable entity to your custom Timespan entity.

    2) Do some silly time-to-ticks conversion, as explained in this blog post.

提交回复
热议问题