[EntityFramework] 对 DateTime 类型使用 SQL 服务器时间或者字段默认值

DateTime 类型在 SQL 服务器上如果设置了默认值,在 EntityFramework 添加新行的时候想使用该默认值,则不能对新增加的实体的 DateTime 字段赋值。

但是如果新增加的实体 DateTime 不设置,会出现错误如下:

System.Data.Entity.Infrastructure.DbUpdateException - An error occurred while updating the entries. See the inner exception for details.
System.Data.Entity.Core.UpdateException - An error occurred while updating the entries. See the inner exception for details.
System.Data.SqlClient.SqlException - The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.

解决方案:

定位到edmx文件,选中该 DateTime 类型的字段,在属性窗口中,将 StoreGeneratePattern 从 None 改为 Computed 即可。

原文地址:https://www.cnblogs.com/lionetchen/p/3966520.html