简体   繁体   English

当值为null时,Entity Framework 6中的Nullable DateTime属性会在保存时引发异常

[英]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)时,我得到:

ControlDate为null

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: 所以我的结论:

  • A model declaring a non-nullable DateTime property will result in a datetime data type in SQL Server. 声明不可为空的DateTime属性的模型将在SQL Server中生成datetime数据类型。
  • An instance of a class declaring a nullable DateTime property will be able to save to the DB as null 声明可以为null的DateTime属性的类的实例将能够作为null保存到DB
  • It is very important to set a valid default date manually (in case <> NULL), otherwise it will set it to 1/1/0001 and throw the exception 手动设置有效的默认日期非常重要 (如果<> NULL),否则将其设置为1/1/0001并抛出异常

据我所知,它实际上是直接映射到.NET的DateTime类型的SQL Server datetime2类型,因此您可能需要在SQL Server中更改列的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM