conversion of a datetime2 data type to a datetime data type error with EF Code first?

Mohammad Zare picture Mohammad Zare · May 14, 2012 · Viewed 42k times · Source

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.

Answer

Blast_dan picture Blast_dan · May 14, 2012

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