conversion of a datetime2 data type to a datetime data type error with EF Code first?
Solution 1
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
Solution 2
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.
Mohammad Zare
A developer that loves clean and meaningful codes
Updated on January 26, 2020Comments
-
Mohammad Zare over 4 years
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.
-
Mohammad Zare almost 12 yearsI'm using Code First and i have no .edmx file.
-
Blast_dan almost 12 yearsI Think what you need to do is specify the column is of type datetime. Did your code first generate the Database? your trying to store a datetime2 object in a datetime column
-
Mohammad Zare almost 12 yearsYes my database generated successfully with code first and that column is of type datetime.
-
Blast_dan almost 12 yearsWhat SQL database are you using?
-
sarin about 8 yearsThis solved it for me. On reflection the error message isn't great. I created a DateTime column, why is it trying to convert it to something else? why not just tell me a constraint has been violated...