[英]Nullable DateTime property in Entity Framework 6 thows exception on save when value is null
I have defined a Nullable DateTime
property in one of my classes: 我在我的一个类中定义了一个Nullable
DateTime
属性:
public DateTime? ControlDate { get; set; }
When using EF 6 CodeFirst to generate the database (SQL Server 2008) from my model I get: 当使用EF 6 CodeFirst从我的模型生成数据库(SQL Server 2008)时,我得到:
The problem is that when I save my instance with ControlDate=null
I get this exception: 问题是,当我使用
ControlDate=null
保存我的实例时,我得到以下异常:
conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value
I have read multiple related posts and articles saying that this usually happens when you define a Non-nullable DateTime property and try to save it without setting a valid date before, and some people suggest setting the property as nullable in case the property value can be null (which is my particular case). 我已经阅读了多个相关的帖子和文章,说这通常发生在你定义一个Non-nullable DateTime属性并尝试保存它而不设置之前的有效日期时,有些人建议将属性设置为可为空,以防属性值为null(这是我的特例)。
My question is: why is EF trying to set a default date when my property and column type are nullable. 我的问题是:为什么当我的属性和列类型可以为空时,EF会尝试设置默认日期。 Null should be a valid value and should flow all the way to the database without any other conversion in between.
Null应该是一个有效值,并且应该一直流到数据库,而不需要在它们之间进行任何其他转换。
Here a related article: Conversion of a datetime2 data type to a datetime data type results out-of-range value 这里有一篇相关文章: 将datetime2数据类型转换为日期时间数据类型会产生超出范围的值
EDIT: : Here is a very similar question . 编辑:: 这是一个非常相似的问题 。 very detailed explanation, in case anyone is interested.
非常详细的解释,如果有人有兴趣。
Lessons Learned: Just wanted to clarify that after looking closer, I figured out it was an issue on my side. 经验教训:只是想澄清一下,仔细观察后,我发现这是我身上的一个问题。 Right before saving my object it was being set to:
在保存我的对象之前,它被设置为:
myObject.ControlDate = new DateTime()
Which, while inspected, it displayed the default incompatible date 1/1/0001
. 在检查时,它显示默认的不兼容日期
1/1/0001
。 Which is well known to cause this exception. 众所周知,这会导致此异常。 So my conclusions:
所以我的结论:
DateTime
property will result in a datetime
data type in SQL Server. DateTime
属性的模型将在SQL Server中生成datetime
数据类型。 DateTime
property will be able to save to the DB as null DateTime
属性的类的实例将能够作为null保存到DB 据我所知,它实际上是直接映射到.NET的DateTime
类型的SQL Server datetime2
类型,因此您可能需要在SQL Server中更改列的类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.