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:
DateTime
property will result in a datetime
data type in SQL Server. DateTime
property will be able to save to the DB as nullAs 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