Saturday, February 28, 2015

How to automatically set DateTimeKind, while fetching Datetime properties from database

In one of the my projects, we were saving all DateTime properties after converting them into UTC timezone.  However while reading these values (using EntityFramework) the DateTimeKind was reset to DateTimeKind.Unspecified.

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.
Three simple steps to get done, lets jump right into the code.

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.
All we are doing here is to apply the attribute to a few properties of our EntityFramework entities.

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!

Credits: SO
Have some Fun!