Saturday, January 19, 2013

Bitten by uninitialized DateTime fields in Entity Framework

I was trying my hands with Ninject, Quartz.Net in an MVC 4 project. Everything was working fine. I added a new model to data project. After adding migration and updating database, I pressed F5.

pofff... the page which was working fine well..., stopped being fine anymore.

I was getting following error:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.

But I was already setting all the date fields and everything was working nicely. After fooling around, it suddenly occured to me that I was not setting a property that is coming from the base class which all the entities were inheriting from.

If the date fields are not initialized (not set), by default it is set to

which of course falls outside the range of the dates acceptable by SQL Server.

The simplest way to get arround is to set the DateTime fields to something acceptable to SQL Server. All worked fine after I added following line:

obj.UpdatedOn = DateTime.Now;