SQL 将 datetime2 数据类型转换为 datetime 数据类型导致超出范围?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7386360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:05:19  来源:igfitidea点击:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range?

sqlsilverlightsql-server-2008silverlight-4.0

提问by Geronimo18

I am working on application contains a datepicker and if I set the time in that picker to a very old value or far in the future when I try to save this value in the database the server throw this exception, what is the cause of it?

我正在处理包含日期选择器的应用程序,如果我将该选择器中的时间设置为一个非常旧的值或很远的将来,当我尝试将该值保存在数据库中时,服务器会抛出此异常,它的原因是什么?

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围。该语句已终止。

回答by AnthonyWJones

DateTimehas the range: January 1, 1753, through December 31, 9999

DateTime范围:1753 年 1 月 1 日至 9999 年 12 月 31 日

DateTime2has the range: 0001-01-01 through 9999-12-31

DateTime2范围为:0001-01-01 到 9999-12-31

So if you are entering a date before 1753 you would get this error when the field in the table is of type DateTime.

因此,如果您输入的日期早于 1753 年,当表中的字段类型为 时,您将收到此错误DateTime

回答by Hari Gillala

Entity Framework will add default date for the field of value {01/01/0001 00:00:00} and this is outside the range of SQL Date Generation. So to make it work, we need to ask EF not to generate a default date, we can make it nullable by doing the following in the Model of that class.

实体框架将为值 {01/01/0001 00:00:00} 的字段添加默认日期,这超出了 SQL 日期生成的范围。所以为了让它工作,我们需要让 EF 不生成默认日期,我们可以通过在该类的模型中执行以下操作来使其可为空。

In this case a default value is generated for the LastLoggedIn field by EntityFramework. If this field in the datebase can take null value, implies we can make it nullable by doing the follwoing in the model

在这种情况下,EntityFramework 会为 LastLoggedIn 字段生成默认值。如果数据库中的此字段可以取空值,则意味着我们可以通过在模型中执行以下操作来使其可为空

 [Display(Name = "LastLoggedIn")]
        public DateTime? LastLoggedIn { get; set; }

回答by Alparslan ?EN

Products prd = new Products();            
prd.CreatedDate = DateTime.Now;

You can add as above

你可以添加如上

回答by Kevin Francis

This error can also be caused by incorrectly spelling the field name in the bind list of a controller action. In my situation, the date was defaulting to an out of range date since the date field wasn't bound as I thought it was.

此错误也可能是由于控制器操作的绑定列表中的字段名称拼写不正确而引起的。在我的情况下,日期默认为超出范围的日期,因为日期字段没有像我想象的那样绑定。