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

4.64 (11 votes)

I managed to generate this error twice within a few days while working with the Entity Framework and SQL Server 2012. I had to resort to searching for a resolution on both occasions so I'm posting about it to sear the cause and solution into my brain.

First, note the exception type. It is a SqlException, so it's being generated by the SqlClient provider. In other words, this is your database talking. The SQL Server datetime datatype  is capable of storing dates in the range 1753-01-01 to 9999-12-31, or Jan 1st 1753 to way longer than anyone reading this needs to worry about. The datetime2 data type was introduced in SQL Server 2008. The range of dates that it is capable of storing is 0001-01-01 to 9999-12-31, or Jan 1st 1 AD to way longer than anyone reading this.... You get the idea.

 

The .Net datetime is isomorphic  with the SQL Server datetime2 type - the range of possible values is the same. The default value for an uninitialised datetime variable is DateTime.MinValue, or 0001-01-01. And this is usually the cause of the error message featured in the title of this post. It happens when you do not provide a value for a datetime in your C# (or VB) code which is to be stored in a non-nullable datetime field in the database. The .Net variable or property will default to 0001-01-01 which SQL Server will see as a valid value for a datetime2 field, but then tries to convert to a datetime type to store it in the appropriate field in the database table. As has already been established, 0001-01-01 is outside of the range of acceptable values for a datetime field. Hence the error message.

So what are the possible fixes? Actually, there are a few:

1. Change the storage to DateTime2 in the database.

Datetime2 is the recommended type for dates and times in SQL Server 2008 onwards.  You will need to explictly map the relevant columns to datetime2 since EF will always map .Net DateTimes to the SQL Server datetime type. You can do this via the fluent API:

modelBuilder.Entity<PageContent>()
    .Property(f => f.DateModified)
    .HasColumnType("datetime2");

 

If you want to do this globally and you are using EF6 or later, you can use custom conventions to specify the mapping:

modelBuilder.Properties<DateTime>()
.Configure(c => c.HasColumnType("datetime2"));

Or you can use attributes on your model's properties:

 [Column(TypeName="datetime2")]
public DateTime DateModified{ get; set; }

Note that these approaches will result in a datetime2 column with a precision of 7 digits (the default and maximum value). If you want to specify an alternative precision, you can only do this via the fluent API at the moment:

modelBuilder.Entity<PageContent>()
    .Property(f => f.DateModified)
    .HasColumnType("datetime2")
    .HasPrecision(0);

2. Change the property to be Nullable

 

You haven't provided a value for the datetime property for one of two reasons: you forgot, or it doesn't need a value. If the reason is that your datetime doesn't actually need a value, then make it nullable. You can do this on your model property by adding a question mark after the data type:

public DateTime? DateModified { get; set; }

Or by using the long hand notation:

public Nullable<DateTime> DateModified { get; set; }

When you next add a migration, it will include an amendment to the database column to allow it to accept null values.

3. Specify a default value within an acceptable range

If you just forgot to provide a value, you can specify a default value for the property to prevent it ever happening again.

public class Myobject
{
    public Myobject()
    {
        DateCreated = DateTime.Now;
    }
    public int Id { get; set; }
    public DateTime DateCreated { get; set; }
}

And there you have it. Incidentally, if you were wondering why the SQL Server datetime data type's minimum value is  a date somewhere in 1753, the answer to this Stackoverflow question will enlighten you.

 

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 70228

7 Comments

- Michel Barbosa

I'd like to thank you for this post.
It helped me a lot !

Regards,

M.Barbosa

- F.Manicou

Thank you so much!!!!

- Ryan Helmoski

Thank you!

- stephen

Thank you, Love all your tutorials :)

- Shaheen

Perfect! Saved me from wasting hours.

- np

Very Nice explaination...thank you..

- Iman

Thanks a lot man. Been searching for this forever :|

Recent Comments

Pam 30/08/2017 11:30
In response to Sending Email in Razor Pages
Mike, RazorPages sound like a nice choice for somebody still working in ASP classic who wants to to...

Robby Robson 15/08/2017 00:43
In response to Routing in Razor Pages
Mike: great stuff. Now that .Core Standard 2.0 is formally out, how soon will you rewrite your book...

Satyabrata Mohapatra 28/07/2017 08:59
In response to Sending Email in Razor Pages
Bit off topic, but congratulation sir for your MVP award. You deserve it !!!...

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...