我正在尝试使用实体框架进行第二次迁移,到目前为止,我已经生成了这样的代码
namespace Entity.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class LedgerDisplayOrder : DbMigration
{
public override void Up()
{
AddColumn("Ledgers", "DisplayOrder", c => c.Int());
// Hic sunt leones
}
public override void Down()
{
DropColumn("Ledgers", "DisplayOrder");
}
}
}
如何填充此列的逻辑实际上非常简单,在SQL中将类似于以下内容:
ALTER TABLE [Ledgers] ADD [DisplayOrder] int null;
UPDATE [Ledgers] SET DisplayOrder = 10 WHERE [Id] = 26 OR [Id] = 27 OR [Id] = 23;
UPDATE [Ledgers] SET DisplayOrder = 20 WHERE [Id] = 29 OR [Id] = 9;
UPDATE [Ledgers] SET DisplayOrder = 30 WHERE [Id] = 28 OR [Id] = 23;
换句话说,应该在迁移过程中自动填充迁移,但是我不确定在// hic sunt leones
处输入什么来实现该目标。我读到我应该使用migrationBuilder class,可能类似于
migrationBuilder.InsertData(table: "ledger", column: "DisplayOrder", value: "10");
但是如何实现WHERE
子句?以及如何加载该课程?我的Visual Studio的快速操作和重构总是建议实现一个新类,所以我必须先安装一些东西吗?
感谢您的任何帮助!
到目前为止,我发现的所有内容都是关于为新列设置默认值。那不是我所追求的。
您可以在迁移过程中使用migrationBuilder.Sql命令执行纯SQL表达式:
migrationBuilder.Sql("UPDATE [Ledgers]
SET DisplayOrder = 10 WHERE [Id] = 26 OR [Id] = 27 OR [Id] = 23; ");