How to work with EF 4.1, CodeFirst C # DateTime datetime2 vs. datetime incompatibility

My code The first models have System.DateTime properties. When the database seeding code is called, it throws this exception:

SqlException (0x80131904): Converting datetime2 data type to datetime data type has exceeded the value.

I am creating a new DateTime object with a constructor. Code First creates a database schema. How can I overcome this obvious error in Code First? I do not really care about my data type. I just need to keep the date and maybe the time of day, but not important.

I looked and read a lot of messages, but none of these errors indicated that they were derived from the data schema created by CodeFirst. The closest answer I found included making changes to the ProviderManifestToken in the edmx file, but my project does not have the edmx file. I did not use the constructor, I use Code First.

+4
source share
2 answers

EF maps DateTime in .NET to DateTime in SQL Server. Types have a different range: DateTime can only store dates later than in 1750. If you try to keep the DateTime in your organization with an earlier date or a unified DateTime (which has year 1), you will get an exception because SQL Server cannot save it.

Decision:

  • Or make sure the dates you want to keep are later than 1750
  • Or map the DateTime properties explicitly to datetime2 in SQL Server, which has a wider range. An example of how to define this mapping to the Fluent API: fooobar.com/questions/245926 / ...

In fact, I also expected datetime2 default mappings, because it works better for DateTime in .NET. But for some reason, they decided to use DateTime by default.

+3
source

Sorry, after more thorough debugging, it turned out that the error came from the initialization of the data object, in which I did not specify values ​​for DateTime .

I thought this comes from a long data sampling statement involving the new DateTime(2012, 2, 19, 19, 0, 0) or some of them. Thanks to Slaum for his efforts - he was right that this was due to unified values.

0
source

Source: https://habr.com/ru/post/1395796/


All Articles