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?
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.
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!
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.
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 :)
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With