1
votes

In database there is a column Created, it has a default GETDATE() so it is assigned on insert automatically. This column is currently not in the model class. When I try to add the property to the model class:

[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Created { get; set; }

and run update-database, it results in the message:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration. You can use the Add-Migration command to write the pending model changes to a code-based migration.

When I tried to allow automatic migration, EF tries to create the DB column Created, but this fails, because the column is already there.

Is there a way to correct the model class?

1

1 Answers

1
votes

Create the empty migration with -IgnoreChanges and apply to the database.

Add-Migration AddsCreatedProperty -IgnoreChanges
Update-Database

You would also want to add the column for any further databases you would bootstrap from your migrations. So in your empty migration add the sql statement in Up method

SQL(@"
    IF NOT EXISTS (
      SELECT *  FROM   sys.columns  WHERE  
        object_id = OBJECT_ID(N'[dbo].[MyTable]')  AND name = 'Created'
    )
    BEGIN
        ALTER TABLE MyTable
        ADD Created DATETIME NOT NULL DEFAULT (GETDATE());
    END
");