Needless to say that, this behavior causes a lot of problems when we want to convert these DateTime properties into different timezone values. What we wanted was, an automatic way to set the DateTimeKind value of our DateTime properties to UTC.
I found an awesomely clean way to do this, without doing it manually for each and every DateTime property.
How Do They Do It!
To get the desired effect we need to follow these steps.
- Create an Attribute that will have the responsibility to set the DateTimeKind value of all eligible DateTime properties of an entity (essentially, those DateTime properties that have this Attribute)
- Apply this attribute on the desired DateTime properties of all entities.
- Lastly, we need to hook up this attribute to the ObjectMaterialized event. So that whenever an entity is materialized, the attribute can perform its job.
The code for this attribute is pretty self explanatory, basically
- It just finds all properties of an entity of type DateTime or DateTime?
- Loops over these properties to find whether they declare the Attribute
- If yes, then set the value of the property along with the desired DateTimeKind value.
Hooking up the Attribute with the ObjectMaterialized event of ObjectContext.
As mentioned earlier, its a simple and clean way to getting the DateTimeKind value set for all DateTime properties of EF entities.
That's all folks!