DateTime and UTC in Entity Framework

c# code-first datetime entity-framework utc


Is it possible to have Entity Framework (I am using the Code First Approach with CTP5 currently) store all DateTime values as UTC in the database?

Or is there maybe a way to specify it in the mapping, for example in this one for the last_login column:

modelBuilder.Entity<User>().Property(x => x.Id).HasColumnName("id");
modelBuilder.Entity<User>().Property(x => x.IsAdmin).HasColumnName("admin");
modelBuilder.Entity<User>().Property(x => x.IsEnabled).HasColumnName("enabled");
modelBuilder.Entity<User>().Property(x => x.PasswordHash).HasColumnName("password_hash");
modelBuilder.Entity<User>().Property(x => x.LastLogin).HasColumnName("last_login");
10/19/2017 2:37:19 PM

Popular Answer

Here is one approach you might consider:

First, define this following attribute:

public class DateTimeKindAttribute : Attribute
    private readonly DateTimeKind _kind;

    public DateTimeKindAttribute(DateTimeKind kind)
        _kind = kind;

    public DateTimeKind Kind
        get { return _kind; }

    public static void Apply(object entity)
        if (entity == null)

        var properties = entity.GetType().GetProperties()
            .Where(x => x.PropertyType == typeof(DateTime) || x.PropertyType == typeof(DateTime?));

        foreach (var property in properties)
            var attr = property.GetCustomAttribute<DateTimeKindAttribute>();
            if (attr == null)

            var dt = property.PropertyType == typeof(DateTime?)
                ? (DateTime?) property.GetValue(entity)
                : (DateTime) property.GetValue(entity);

            if (dt == null)

            property.SetValue(entity, DateTime.SpecifyKind(dt.Value, attr.Kind));

Now hook that attribute up to your EF context:

public class MyContext : DbContext
    public DbSet<Foo> Foos { get; set; }

    public MyContext()
        ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
            (sender, e) => DateTimeKindAttribute.Apply(e.Entity);

Now on any DateTime or DateTime? properties, you can apply this attribute:

public class Foo
    public int Id { get; set; }

    public DateTime Bar { get; set; }

With this in place, whenever Entity Framework loads an entity from the database, it will set the DateTimeKind that you specify, such as UTC.

Note that this doesn't do anything when saving. You'll still have to have the value properly converted to UTC before you try to save it. But it does allow you to set the kind when retrieving, which allows it to be serialized as UTC, or converted to other time zones with TimeZoneInfo.

9/23/2014 8:03:31 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow