Change data in migration Up method - Entity Framework

Instead of using the Sql method you could also use the UpdateData method.

migrationBuilder.UpdateData(
    table: "RequestValidationErrors", 
    keyColumn: "WordCode", 
    keyValue: "RequestValidationError.MoreThanOneItemFound", 
    column: "IsBreaking", 
    value: false);

(I don't know if only ef core supports this method)


If you want to use the framework for changes like this, you should separate Database changes from Data changes.

Create a migration for just the Database changes, and execute.

Then create a new migration (the Up() and Down() methods will be empty). You can now instantiate your DatabaseContext and there will be no error. This way you can use the Framework for these changes, and properly implement a Down() method.


In the middle of a migration, it's better to use Sql() method to update database data.

Sql("UPDATE dbo.RequestValidationErrors SET IsBreaking = 0 WHERE WordCode = 'RequestValidationError.MoreThanOneItemFound'");

Also you should define the default value for the new column. So the solution should be something like this:

public override void Up()
{
    AddColumn("dbo.RequestValidationErrors", "IsBreaking", c => c.Boolean(nullable: false, default: true));
    Sql("UPDATE dbo.RequestValidationErrors SET IsBreaking = 0 WHERE WordCode = \"RequestValidationError.MoreThanOneItemFound\"");
}

Using a DbContext in the middle of its migration is very ambiguous. What do you expect from the context? It has the after migration state in its models, but the database has the before migration state in the tables. So the model and database do not match. If you still insist on using DbContext in your code, disabling the model checking might be the solution. You can disable model checking using:

Database.SetInitializer<Log4ProContext>(null);

UPDATE:

As of EF Core 2.1 you can use UpdateData instead of Sql method for simpler cases just as @ntfrex mentioned in an answer:

migrationBuilder.UpdateData(
    table: "RequestValidationErrors", 
    keyColumn: "WordCode", 
    keyValue: "RequestValidationError.MoreThanOneItemFound", 
    column: "IsBreaking", 
    value: false);

My advice is NOT TO USE nameof operator for table and column names nowhere in migrations at all. As renaming these classes later would cause the old migrations to fail in production as the table names in the database are still with the old name.