This question already has an answer here:
- Entity Framework DateTime and UTC 10 answers
I have C# program where all DateTime
objects are DateTimeKind.UTC
. When saving the objects to the database it stores UTC as expected. However, when retreiving them, they are DateTimeKind.Unspecified
. Is there a way to tell Entity Framework (Code First) when creating DateTime
objects in C# to always use DateTimeKind.UTC
?
My solution, using code first: Declare the DateTime properties in this way:
Also can create the property as:
ToKindUtc()
is a extension to changeDateTimeKind.Unspecified
toDateTimeKind.Utc
or callToUniversalTime()
if kind isDateTimeKind.Local
Here the code for the extensions:Remember to include in the model's file.
The set method of property is called when reading from datatabase with EF, or when assigned in a MVC controller's edit method.
Warning, if in web forms, if you edit dates in local timezone, you MUST convert the date to UTC before send to server.
You can have your datacontext fix up all the relevant values as it goes. The following does so with a cache of properties for entity types, so as to avoid having to examine the type each time:
This can also be combined with attributes so as to allow one to set the
DateTimeKind
each property should have, by storing a set of rules about each property, rather than just thePropertyInfo
, and looking for the attribute inGetDateProperties
.No, there's not. And it's actually
DateTimeKind.Unspecified
.However, if you are concerned about supporting multiple timezones, you should consider using DateTimeOffset. It's like a regular DateTime, except that it does not represent a "perspective" of time, it represents an absolute view, in which 3PM (UTC - 3) equals 4PM (UTC - 2). DateTimeOffset contains both the DateTime and the time zone and it's supported by both EntityFramework and SQL Server.
Have a look on the michael.aird answer here: https://stackoverflow.com/a/9386364/279590 It stamp the date UTC kind during loading, with an event on ObjectMaterialized.