I'm using EF Code first with my asp.net mvc application. here is my code:
Request.RequestDate = DateTime.Now;
the type of RequestDate is datetime in my database. and this is error that occurred when i use the above code!:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
please help me. thanks.
Microsoft recommends using DateTime2 instead of DateTime as it is more portable and provides more seconds precision. Also, DateTime2 has a larger date range and optional user-defined seconds precision with higher accuracy. Datetime2 aligns with SQL standards.
Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.
Edit:
How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?
The issue is that you are trying to save a value that cannot fit in a SQL datetime column. the answer givin here will stop the conversion from failing.
or in your Database change the columns to be type datetime2. I don't exactly know why they code first is generating datetime columns instead of datetime2
Here is an example to explicitly map your Datetime columns to datetime2 in SQL
Using DateTime properties in Code-First Entity Framework and SQL Server
On my side it was because the datetime was not nullable and in some situation the field was not initialized in the constructor. I solved this by setting my field as nullable
public DateTime? MyDate { get; set; }
Another solution would be to initialize the field in the constructor no matter what.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With