Is there a way to make Entity Framework Core let you use a DateTime for a SQL Time column? SQL Server allows you to set a Time column value using a DateTime, but when you try to configure Entity Framework Core to do this, it throws an exception when compiling the model saying that the Database Provider does not support the datatype.
This code throws the exception
public void Configure(EntityTypeBuilder<Category> builder)
{
...
builder.Property<System.DateTime>(x => x.StartTime).HasColumnName(@"StartTime").HasColumnType(@"time").IsRequired()
// HasColumnType matches the type defined in SQL
}
This code works fine, but I'd rather keep HasColumnType accurate so that it doesn't modify the database to use DateTime instead of Time...
public void Configure(EntityTypeBuilder<Category> builder)
{
...
builder.Property<System.DateTime>(x => x.StartTime).HasColumnName(@"StartTime").HasColumnType(@"datetime").IsRequired()
// HasColumnType does not match the type defined in SQL
}
Is there a reason EF Core blocks the ability to do this when SQL allows it?
Timespaninstead. Atimecolumn contains only the time-of-day, it's not a fulldatetimeso it shouldn't be mapped toDateTimedatetimetype has a lot of quirks - you could add twodatetimevalues and get a date in 4040 for example. That doesn't mean it's a good idea. That's why SQL Server doesn't allow implicit conversions betweentimeand the newer types likedatetime2DateTimethat's terrible. Time-of-Day doesn't have a date component at all, so what is aDateTimesupposed to mean? How could you compare times when all you have areDateTimevalues? WhileTimespanmay not be restricted to just 24 hours, it's a lot better thanDateTimethough. There's no need for a custom binder either -timemaps toTimespan, notDateTimetimemap toTimespanin EF.