An overflow occurred while converting to datetime using EF4

假装没事ソ 提交于 2019-11-28 21:14:17

If your model has non-nullable property of type DateTime, when you post a form with empty value for that property, it is automatically set to DateTime.MinValue, which is in .net 01/01/0001 (DateTime.MinValue on MSDN)

(As a side note, you can change this behavior by implementing your own IModelBinder for DateTime which could i.e. throw a validation exception if attempted value is null/empty and property is not nullable).

If you try to save that value (DateTime.MinValue) into database, you will get conversion error if database field is of sql type datetime, because .net DateTime.MinValue is less than SQL datetime minvalue (01/01/1753) and therefore cannot be converted to sql value. (SQL datetime min value on MSDN)

This error will not occur on newer versions of MS SQL Server, which have datetime2 datatype which allows values from 01/01/0001 to 31/12/9999 (SQL datetime2 on MSDN) (if datetime2 is used for that field, of course).

This is an old question ... but maybe somebody could find this helpful:

I solved the problem (MVC4, EF5, SqlServerCE 4.0) using following definition:

public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }

Have fun!

I hade the same issue, the dateTime propety being saved on an object to the database was null initially.

Verify that an actually datetime has been assigned before saving the object to the local CE database.

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