Conversion of a datetime2 data type to a datetime data type results out-of-range value

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Message par ForumBot »

Conversion of a datetime2 data type to a datetime data type results out-of-range value
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Conversion of a datetime2 data type to a datetime data type results out-of-range value

Message par ForumBot »

Short Answer

This can happen if you do not initialize a value to a ***DateTime*** field; the field does not accept ***NULL*** values, and it's a value type, so the default value of the non-nullable DateTime type will be used.

Setting the value fixed it for me!

Long Answer

The value of `default(DateTime)` is `DateTime.MinValue` (or `new DateTime(1, 1, 1)` or 01/01/0001), which is not a valid SQL `datetime` value.

The lowest valid value for SQL Server datetime is [`01/01/1753`](https://stackoverflow.com/questions/3310569/what-is-the-significance-of-1-1-1753-in-sql-server) due to its use of a Gregorian calendar. SQL Server DateTime2 however supports dates starting at 01/01/0001. Entity Framework by default uses DateTime2 for representing dates, so the generated SQL is implicitly coercing the generated DateTime2 value to a DateTime value on the SQL Server-side.
Répondre

Revenir à « .NET & C# »