This seems to work for me:
public partial class MyDbContext : DbContext
{
...
/// <summary>
/// Deserializes DateTime so if its Kind is Unspecified then it's set to Utc.
/// Does nothing on Serialization as SQL Server discards this info when saving to DateTime fields.
/// </summary>
public class DateTimeToUtcConverter : ValueConverter<DateTime, DateTime>
{
public DateTimeToUtcConverter() : base(Serialize, Deserialize, null)
{
}
static Expression<Func<DateTime, DateTime>> Deserialize =
x => x.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(x, DateTimeKind.Utc) : x;
static Expression<Func<DateTime, DateTime>> Serialize = x => x;
}
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
// Configure ALL the DateTime properties in our EF model so they'll have DateTime.Kind set to Utc.
// (We'll also have to do this manually for any SQL queries we don't use EFCore to map to objects)
configurationBuilder
.Properties<DateTime>()
.HaveConversion<DateTimeToUtcConverter>();
}
}
I added a comment here, perhaps wiser people will reply with a better solution.