Monday, July 1, 2013

Resolve Entity Framework error conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

I recently encountered this exception:

“System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.”

This happened on an Entity Framework 5.0 code-first project.  The cause of this exception was an attempt to save the C# DateTime.MinValue to a SQL Server datetime not null column.  DateTime.MinValue is 1/1/0001 whereas the minimum allowable SQL Server datetime is 1/1/1753, hence the out-of-range error.  The reason this happened was that a new POCO entity instance did not have the corresponding DateTime property explicitly set to a value, so it defaulted to DateTime.MinValue and then resulted in the out-of-range exception when EF attempted to insert the POCO instance.