L_7337
L_7337

Reputation: 2748

SaveChangesAsync Error: Conversion of DateTime2 to DateTime Out-Of-Range

I know this question has been asked a bunch of times on StackOverflow, but none of the answers seem to fit my situation, or they just tell them to allow NULL fields in their DateTime (which I don't want to do).

Here is the code:

public async Task<int> CreateJobAsync(JobViewModel jvm)
    {
        Job j = new Job();
        j.Name = jvm.Name;
        j.UserId = jvm.UserId;
        j.ClassDefinition = jvm.ClassDefinition;
        j.DaysToRun = jvm.DaysToRun;
        j.ToEmail = jvm.ToEmail;
        j.Active = true;
        j.CreatedDate = DateTime.Now;
        j.ModifiedDate = DateTime.Now;

        context.Jobs.Add(j);
        var result = await context.SaveChangesAsync();

        return result;
    }

All my fields in the Job class are DateTime as are the object in the database. The date values are not NULL. When I run Sql Profiler, it doesn't even show that a database call was made.

The Error occurs on the await call and it is:

conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

This seems like a fairly easy example and I do need these values to be not null. Any other ideas???

Upvotes: 0

Views: 561

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

There must be other field(s) in Job that are of type DateTime that are not being set in your code. This unset property will default to DateTime.MinValue which is 1-Jan-0001. The SQL type DATETIME only supports dates with a year greater than 1752. Hence, the reason for your exception.

The easiest solution is to change the database to use DATETIME2 and not DATETIME. See also DateTime2 vs DateTime in SQL Server

Upvotes: 2

Arghya C
Arghya C

Reputation: 10078

DateTime is a value type in .Net and will never be null.

Now, being said that, the default value for DateTime is DateTime.MinValue in C# which equals to 01/01/0001, and all DateTime fields get this value by default, unless otherwise specified! But, this date is out of SQLServer date ranges, for which minimum date is 1/1/1753. Probably that's why you are getting this exception.

One way to make your code usable will be to use SqlDateTime.MinValue instead of DateTime.MinValue.

Upvotes: 2

Related Questions