5

I'm using ASP.Net 4 EF 4.3.1 Code First Migrations.

I have an existing model class. I've added a property to it:

public DateTime LastUpdated { get; set; }

When I run update-database -force -verbose I get:

ALTER TABLE [MyTable] ADD [LastUpdated] [datetime] NOT NULL DEFAULT '0001-01-01T00:00:00.000'
System.Data.SqlClient.SqlException (0x80131904): The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.

I'm going to guess this relates to the implied default value being used in the generated SQL - it would appear to be complaining that the varchar it used to initialize things is data lost.

Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
  • It's not my default - EF Code First Migrations is generating this SQL automatically for any new, not-null DateTime property/column. – Chris Moschini Jun 06 '12 at 07:54
  • The SQL `DateTime` datatype has a min value of 1 jan 1753. The .NET Datetime has a min value of 1 jan 0001. Unfortunately, conflicts are common. – Anders Abel Jul 04 '12 at 08:33

1 Answers1

8

The answer to this problem of not being able to add a non-null DateTime column is the same as the problem of getting 2 default values specified for a DateTime column: EF 4.3.1 Migration Exception - AlterColumn defaultValueSql creates same default constraint name for different tables

That is, it's been broken a long time, and you can workaround it by migrating with it nullable:

public DateTime? LastUpdated { get; set; }

PM> update-database

Then migrate again with it not null to get where you intended:

public DateTime LastUpdated { get; set; }

PM> update-database
Community
  • 1
  • 1
Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
  • In my case, it was necessary to remove `.IsRequired()` in fluent api too before to put it back. Thanks – A. Morel Feb 09 '22 at 10:50