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

前端 未结 2 618
渐次进展
渐次进展 2020-12-03 18:52

I am saving a Cart object to the database that has a nullable datetime. This is the error I get:

The conversion of a datetime2 data type to a datetime da

相关标签:
2条回答
  • 2020-12-03 19:15

    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.

    0 讨论(0)
  • 2020-12-03 19:15

    The EF Team actually discussed this particular item during one of the design meetings. The decision was to leave the current behavior as is. Here are the meeting notes that can give you more context.

    0 讨论(0)
提交回复
热议问题