use*_*662 12 c# nullable rollback fluent-migrator
鉴于以下迁移:
[Migration(1)]
public class Mig001 : Migration
{
public override void Up()
{
Alter.Table("foo").AlterColumn("bar").AsInt32().Nullable();
}
public override void Down()
{
Alter.Table("foo").AlterColumn("bar").AsInt32().NotNullable();
}
}
Run Code Online (Sandbox Code Playgroud)
迁移器更改列并使其可为空,并且在回滚时它会执行相反操作并使其不再可为空.
让我们说foo自迁移以来已经添加了数据; 现在列中有null的bar行.
如果它被回滚然后操作将失败,在fluentmigrator中是否有办法处理这种情况?或者什么是最佳实践.
Dan*_*Lee 11
简短的回答是为具有可空值的所有列设置默认值.您可以使用Execute.Sql表达式使用sql执行此操作.这应该在Alter.Table表达式之前.
public override void Down()
{
Execute.Sql("update foo set bar = 0 where bar is null");
Alter.Table("foo").AlterColumn("bar").AsInt32().NotNullable();
}
Run Code Online (Sandbox Code Playgroud)
长期的答案是,要始终确保您可以回滚迁移并且确定需要这样做,需要做很多工作吗?
例如,如果后续行动是创建一个表,并向下运动砸,你应该保存在一个临时表中的数据,以便它不会消失?对于大多数用例,在测试环境中部署或回滚失败的部署时使用向下操作,并且在部署之后很少回滚迁移.
以下是执行迁移的另一种方法,不需要直接执行SQL.
public override void Down()
{
Update.Table("foo").Set(new { bar = 0 }).Where(new { bar = (int?) null });
Alter.Table("foo").AlterColumn("bar").AsInt32().NotNullable();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5012 次 |
| 最近记录: |