2011/01/17

EF save datetimes in UTC to data base

When you work with various timezones, a good approach to work with dates its store in UTC in database because of databases lack of support for timezones, NET side have tools to work with (DateTime.UtcNow, DateTime.ToLocalTime, TimeZoneInfo) so comfortable, but you need to convert to UTC when you store to database.

One transparent solution is tuning ObjectContext:



First we need to convert all DateTimes to UTC previous save in database:



DateTime class, has a property Kind of type DateTimeKind enumeration with values Unspecified, Utc, Local, our enemy its Unspecified, if you save a entity with a property with DateTime.Kind Unespecified you get the ArgumentException in runtime (sorry no compiler check).
Be aware when you parse DateTime its Kind by default its Unspecified.

And when load from database set de Kind to UTC for all DateTimes:



Disclaimer: This is my first attempt to write something meaningful in Shakespeare language.

No hay comentarios: