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

余生颓废 提交于 2019-12-17 09:38:41

问题


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.


回答1:


DateTime has the range: January 1, 1753, through December 31, 9999

DateTime2 has the range: 0001-01-01 through 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.




回答2:


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.

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

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



回答3:


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

You can add as above




回答4:


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.



来源:https://stackoverflow.com/questions/7386360/the-conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!