简体   繁体   中英

EF6 datetime2 conversion to datetime resulted in an out-of-range value

I've just deployed server code that used to work literally a week ago. The part of the code that results in the error did not change, however the object itself did.

It is a Model First approach (converted from Database First), and I've added two association fields and two new tables to the model.

The part of the code that throws the error is mission critical. It basically disables concurrent editing of the value by setting a timestamp. However for some reason it does not work.

The particular code:

user.AlertConcurrency = DateTime.UtcNow;
db.SaveChanges();

The error:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

Now, the user.AlertConcurrency field is a datetime type in the database. I don't see why it even tries to do datetime to datetime2 conversion here. What am I missing?

datetime2 has a larger range that datetime, so you probably have a null datetime2 which is "0001/01/01" trying to be converted into a datetime which the min value is "1753/01/01" thus the conversion fails. A null C# DateTime property would thus be your datetime2 value thats causing the problem.

Check your model is fully updated/in sync with your database and check for null values in your DateTime properties. If you have null database values or want to save null DateTime then consider using the nullable DateTime in your model and database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM