Change data in migration Up method - Entity Framework

后端 未结 4 1484
一向
一向 2020-12-14 05:48

I have added a new property into my existing model. It\'s a bool property with default value true. There are existing data in this table and I would like to set one specific

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 06:17

    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(null);
    

提交回复
热议问题