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.

3 comments:

  1. Did you ever solve this i have the same issue

    ReplyDelete
    Replies
    1. Make sure your POCO DateTime fields default to some value that is at least 1/1/1753, which means you can't default to DateTime.MinValue. This is only an issue for DateTime fields, not for nullable (DateTime?) fields.

      Delete
  2. how you solve this issue because i have the same issue

    ReplyDelete