3

So the problem is that I can't set the model so that the migration will show DateTimeKind.Utc instead of DateTimeKind.Unspecified I'm doing this:

contactsConfiguration
   .Property(c => c.DateAdded)
   .ValueGeneratedOnAdd()
   .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc))

Any ideas?

Henrik Wilshusen
  • 289
  • 1
  • 11
Marek M.
  • 3,799
  • 9
  • 43
  • 93
  • I had the same problem and used https://stackoverflow.com/a/19301623/3937941 Hope it helps. – Zysce Aug 10 '18 at 13:32
  • 1
    If you care about offsets use `DateTimeOffset` as a property and database field type, not `DateTime` with an *assumed* UTC value. `datetime` in the database has *no* indication that it's UTC or local (local to whom?). – Panagiotis Kanavos Aug 10 '18 at 13:58
  • BTW that migration has no meaning precisely because the `datetime` database type has no DateTimeKind. – Panagiotis Kanavos Aug 10 '18 at 14:01

1 Answers1

2

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.

Rory
  • 40,559
  • 52
  • 175
  • 261
  • Ah, now I found basically the same thing here - https://stackoverflow.com/a/73154546/8479 – Rory Nov 26 '22 at 20:24