Nullable DateTime property in Entity Framework 6 thows exception on save when value is null

.net c# datetime entity-framework-6

Question

I have defined a Nullable DateTimeproperty in one of my classes:

public DateTime? ControlDate { get; set; }

When using EF 6 CodeFirst to generate the database (SQL Server 2008) from my model I get:

ControlDate null

The problem is that when I save my instance with ControlDate=null I get this exception:

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

I have read multiple related posts and articles saying that this usually happens when you define a Non-nullable DateTime property and try to save it without setting a valid date before, and some people suggest setting the property as nullable in case the property value can be null (which is my particular case).

My question is: why is EF trying to set a default date when my property and column type are nullable. Null should be a valid value and should flow all the way to the database without any other conversion in between.

Here a related article: Conversion of a datetime2 data type to a datetime data type results out-of-range value

EDIT: : Here is a very similar question. very detailed explanation, in case anyone is interested.

Lessons Learned: Just wanted to clarify that after looking closer, I figured out it was an issue on my side. Right before saving my object it was being set to:

myObject.ControlDate = new DateTime()

Which, while inspected, it displayed the default incompatible date 1/1/0001. Which is well known to cause this exception. So my conclusions:

  • A model declaring a non-nullable DateTime property will result in a datetimedata type in SQL Server.
  • An instance of a class declaring a nullable DateTimeproperty will be able to save to the DB as null
  • It is very important to set a valid default date manually (in case <> NULL), otherwise it will set it to 1/1/0001 and throw the exception
1
4
5/23/2017 11:52:56 AM

Accepted Answer

As far as I'm aware, it's actually the SQL Server datetime2 type that maps directly to .NET's DateTime type, so you may need to change the type of your column in SQL Server

4
9/2/2014 12:39:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow