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

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.