Why does EF5 code first use datetime2 when inserting a nullable datetime into the database?

The DateTime type in .NET has the same range and precision as datetime2 in SQL Server. When EF inserts or updates a datetime or datetime2 column in SQL Server it converts the model property to the type that can hold the whole range of DateTime in .NET, that’s datetime2. Converting into datetime would fail if the DateTime property is not inside the range of datetime in SQL Server.

The problem that causes the exception are, by the way, not the two nullable OpeningDateUtc and ClosingDateUtc columns, but the CreatedOnUtc value which is '0001-01-01 00:00:00' in your SQL snippet, i.e. CreatedOnUtc is apparently not initialized in your model entity. The earliest date that datetime in SQL Server can store is in the year 1750, so year 0001 won’t fit into the type (but it would fit into datetime2).

So, solution is to either set CreatedOnUtc to a valid datetime value or – as you know – define the types as datetime2 in your mapping.

But I agree, there would be less confusion if EF would map DateTime properties by default to datetime2.

Leave a Comment