I have defined a Nullable DateTime
property 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:
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 adatetime
data type in SQL Server. - An instance of a class declaring a nullable
DateTime
property 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