更改迁移数据Up方法 - 实体框架 [英] Change data in migration Up method - Entity Framework

查看:143
本文介绍了更改迁移数据Up方法 - 实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在现有的模型中添加了一个新的属性。这是一个bool属性,默认值为true。在此表中有现有数据,我想在Up方法中创建新字段之后,将特定行的新属性设置为false。

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 row's new property to false right after creating the new field, in the Up method.

public override void Up()
    {
        AddColumn("dbo.RequestValidationErrors", "IsBreaking", c => c.Boolean(nullable: false));
        using (Context ctx = new Context())
        {
            var validation = ctx.RequestValidationErrorSet.FirstOrDefault(x => x.WordCode == "RequestValidationError.MoreThanOneItemFound");
            if (validation != null)
            {
                validation.IsBreaking = false;
                ctx.SaveChanges();
            }
        }
    }

这样EF会抛出错误在说

This way EF throws an error during saying


System.InvalidOperationException:自创建数据库以来,
'DbContext'上下文的模型已更改。
考虑使用代码优先迁移来更新数据库

System.InvalidOperationException: The model backing the 'DbContext' context has changed since the database was created. Consider using Code First Migrations to update the database

是否可以在这里更改数据库,或者我应该在其他地方?

Is it possible to change the database here or should I do it elsewhere?

推荐答案

在迁移过程中,最好使用 Sql()更新数据库数据的方法。

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\"");
}

使用 DbContext 在它的迁移中间是非常模糊的。你从上下文中期望什么?它的模型中具有迁移后状态,但数据库在表中具有迁移前状态。所以模型和数据库不匹配。如果您仍然坚持在您的代码中使用 DbContext ,则禁用模型检查可能是解决方案。您可以使用以下方式禁用模型检查:

Using a DbContext in the middle of it's 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 are not match. If you still insist on using DbContext in your code, disabling model checking might be the solution. You can disable model checking using:

Database.SetInitializer<Log4ProContext>(null);

这篇关于更改迁移数据Up方法 - 实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆