Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value."

SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

my code is like this:

        using (var contxt = new realtydbEntities())
        {
            var status = GetStatus();

            var repIssue = new RepairIssue()
            {
                CreaterId = AuthorId,
                RepairItemDesc = this.txtDescription.Text,
                CreateDate = DateTime.Now,//here's the problem
                RepairIssueStatu = status
            };

            contxt.AddObject("RepairIssues", repIssue);
            contxt.SaveChanges();
        }

the CreateDate property mapping to a column which type is smalldatetime.

how to make this code run?

like image 531
Scott 混合理论 Avatar asked May 08 '12 08:05

Scott 混合理论


People also ask

How do you fix the conversion of a varchar data type to a datetime data type resulted in an out of range value?

Answer: The error is due to an invalid date format being saved to the custom_rmh_rooms_history SQL table. To resolve this issue, the Windows Regional settings need to be modified and the Short Date format needs to be in MM/dd/yyyy format.

What is the difference between datetime and Datetime2?

The main difference is the way of data storage: while in Datetime type, the date comes first and then time, in Datetime2, 3 bytes, in the end, represents date part!

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

I had the same exception, but it was because a non nullable datetime property that taking the min datetime value. That wasn't a smalldatetime at DB, but the min datetime of C# exceed the limit of min datetime of SQL. The solution was obvious, set the datetime properly. BTW, the code wasn't mine, and that's why I wasn't aware of that property :)

like image 185
Milton Avatar answered Sep 26 '22 00:09

Milton


The root of your problem is that the C# DateTime object is "bigger" than SQL's smalldatetime type. Here's a good overview of the differences: http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

So really your options are:

  1. Change the column type from smalldatetime to datetime (or datetime2)
  2. Instead of using EF, construct your own SQL Command (and you can use SqlDateTime)
like image 23
Jason Avatar answered Sep 27 '22 00:09

Jason