Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default dateTime value in EF Core

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?

like image 892
Marek M. Avatar asked Sep 02 '25 14:09

Marek M.


1 Answers

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.

like image 55
Rory Avatar answered Sep 05 '25 03:09

Rory