3

Using EF 6. I have an entity (Person) that contains a nullable datetime field.

public DateTime? StartDate { get; set; }

This made me think I should be able to assign null to this property without any issue, like this ...

Person.StartDate = null;

However, when I get to context.SaveChanges() I get an error saying ...

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated."

Shouldn't a nullable field be able to accept .... null?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
webworm
  • 10,587
  • 33
  • 120
  • 217

1 Answers1

3

Make your database column nullable too.

robrich
  • 13,017
  • 7
  • 36
  • 63
  • I am using EF Code Migrations so the C# code is generating the database. Shouldn't the database column be nullable already since I defined it as `DateTime?` Do I need to add perhaps a data annotation to the entity? I also looked at the generated schema and the field is listed as able to accept null in the database – webworm Feb 04 '16 at 00:06
  • Still worth a double check against the actual database table DDL itself. – code4life Feb 04 '16 at 00:10
  • `datetime2` column type can support dates before 1753 while `datetime` can't. Why is null tripping this? Not sure. Why 1753? http://stackoverflow.com/questions/3310569/what-is-the-significance-of-1-1-1753-in-sql-server – robrich Feb 04 '16 at 00:12
  • @code4life - I agree, worth a check. However, the database shows the field as `StartDate (datetime, null)` – webworm Feb 04 '16 at 00:16
  • In general, I hit this error when I'm not using `null` but rather when I'm using `DateTime.Min` or `new Date(1,1,1)`. Are you sure you're saving `null` and not accidentally initializing it to something else? – robrich Feb 04 '16 at 00:21
  • @robrich, How can I set the field as null on database? – Rafael Guimarães Oct 11 '19 at 01:24
  • @RafaelGuimarães pop open SQL Management Studio or phpMyAdmin or your DB editor of choice and look at the table definition. There's probably a nullable check-box for this column. – robrich Oct 18 '19 at 18:28
  • @robrich In mongodb? on a sql database I know how do it, but in mongodb? nosql... – Rafael Guimarães Oct 19 '19 at 18:24
  • @RafaelGuimarães MongoDB has no schema, so I'm really surprised you're getting null errors. Sounds like a `[Required]` attribute on a C# class. – robrich Oct 20 '19 at 20:40
  • @robrich exactly! In doctrine ODM ? – Rafael Guimarães Oct 21 '19 at 21:27