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

.net c# datetime entity-framework-6


I've created a Nullable.DateTime a characteristic in one of my classes:

public DateTime? ControlDate { get; set; }

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

ControlDate null

When I save my instance with, there is a problem becauseControlDate=null With this exception, I

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

This commonly occurs when you define a Non-nullable DateTime property and attempt to save it without setting a valid date beforehand, according to a number of linked posts and articles. Some people advise declaring the property as nullable in case the property value could be null (which is my particular case).

Why is EF attempting to define a default date when my property and column type are nullable is the question I have. Null ought to be a valid value that flows directly into the database without any intermediate conversions.

Here is an associated article: Out-of-range values are produced when a datetime2 data type is converted to a datetime data type.

EDIT: zzz45zzz. a pretty thorough explanation, for anyone who might be interested.

Lessons Discovered Just wanted to be clear that I discovered it was a problem on my end after taking a closer look. Prior to saving my item, the following settings were made:

myObject.ControlDate = new DateTime()

This, upon inspection, revealed the standard incompatible date.1/1/0001 . This is recognized to be the reason for this exception. hence, my judgments:

  • Modeling a non-nullable and declaring itDateTime property will lead todatetime kind of data in SQL Server.
  • a class instance that declares a nullableDateTime property can be saved to the database as null.
  • It is really crucial. to manually set a proper default date (in the event that > NULL), else, it will set it to January 1, 0001 and raise an exception.
5/23/2017 11:52:56 AM

Accepted Answer

It is, as far as I know, the SQL Server.datetime2 type that closely corresponds to. NET'sDateTime You might need to alter the type of your column in SQL Server as a result.

9/2/2014 12:39:36 PM

Related Questions


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