Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 460
Mohammad Zare Avatar asked May 14 '12 14:05

Mohammad Zare


People also ask

What is the difference between DateTime and DateTime2?

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.

What is DateTime2 SQL?

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.


2 Answers

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

like image 93
Blast_dan Avatar answered Oct 04 '22 10:10

Blast_dan


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.

like image 44
Daniel Avatar answered Oct 04 '22 08:10

Daniel