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");
Best Answer
Here is one approach you might consider:
First, define this following attribute:
Now hook that attribute up to your EF context:
Now on any
DateTime
orDateTime?
properties, you can apply this attribute: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
.