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

4.5 (8 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: 67188

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

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...

Mau 06/06/2017 08:58
In response to Razor Pages - The Elevator Pitch
I am missing the razor view code. Thank you for your article. Design pattern should improve the of...

Obinna Okafor 26/05/2017 16:16
In response to Razor Pages - The Elevator Pitch
Thank you for this wonderful piece, Mike. I need more of these...Keep them coming - anything more...

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...