Storing TimeSpan with Entity Framework Codefirst - SqlDbType.Time overflow

后端 未结 4 788
攒了一身酷
攒了一身酷 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:06

    Doing a time-to-ticks conversion on both ends is no longer silly. Not sure when they added it, but Entity Framework will now select the appropriate built in converter if one exists (in this case TimeSpanToTicksConverter). All you need to do is add a single attribute to your entity class and Entity Framework will automagically give the column in the SQL table the same range as the TimeSpan class.

    public class Stage
    {
        public string Name { get; set; }
    
        [Column(TypeName = "bigint")]
        public TimeSpan Span { get; set; }
    
        public int StageId { get; set; }
    }
    

    I'm sure bigint isn't the default column type for TimeSpan for human readability and backwards compatibility, but this seems like a pretty much perfect solution.

    I hope this helps anybody experiencing this issue six years later.

    Documentation: https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions

提交回复
热议问题