Bronzato
Bronzato

Reputation: 9342

Manually modifying EF Code First Migration step without perturbations

I know we cannot manually update code inside DbMigration method because this can lead us to an inconsistent state for the next DbMigration step.

So, for example, if I change nullable: false to nullable: true in the code of the DBMigration step below (and at the same time do the same modification in the entity class) this will certainly gives problems. The right way is to apply modification only inside the entity class and to add an new DBMigration step in the Package Manager Console (Add-Migration).

public partial class AddDisabledOnUser : DbMigration
{
    public override void Up()
    {
        AddColumn("dbo.Users", "Disabledc => c.Boolean(nullable: false));
    }

    public override void Down()
    {
        DropColumn("dbo.Users", "Disabled");
    }
}

But what about DBMigration step with SQL commands like below:

public partial class UpdateSomeUsers : DbMigration
{
    public override void Up()
    {
        Sql("UPDATE Users SET Remark = 'Blah blah' WHERE UserName like 'ABC'");
    }

    public override void Down()
    {

    }
}

Thanks.

Upvotes: 0

Views: 648

Answers (1)

Francesc Castells
Francesc Castells

Reputation: 2847

Changing a migration which has already been applied to the DB won't have any effect, therefore I assume you want to change a migration before running it against the DB. If this is the case, then your problem is not really a problem:

  1. If you want to change a property or another aspect of the model, do it, then add the same migration again with the -Force switch, or delete the migration and add it again. Now the migration will match your model just fine
  2. If you want to add extra SQL statements, just do it as you mention adding one or more Sql("...") to the migration file. It doesn't make a difference how many times you change them.

The only problem with manually modifying the migration file is that if you have to recreate the migration, you have to be careful not to forget to add the manual changes again. To avoid that, what I do is to customize the migrations SQL generation so that I can specify my custom SQL code in the mapping files.

Upvotes: 1

Related Questions