我正在使用Entity Framework和代码优先方法。
我创建了一个我映射为表的类:
modelBuilder.Entity<CdrFile>()
.ToTable("cdrFile", schemaName)
.HasKey(f => new { f.Id });
我创建了迁移CdrFileMigration
。这是最后迁移。
public override void Up()
{
CreateTable(
"administration.cdrFiles",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(),
fileNameWithExtension = c.String(), // <-- See this line
url = c.String(),
serviceType = c.String(),
date = c.DateTime(nullable: false),
state = c.Int(nullable: false),
operatorName = c.String(),
acquisitionDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
}
然后我更新了db。
一段时间过去了,我更改了实体CdrFile
删除列。
同时没有创建迁移。所以我将数据库更新为之前的版本。我修改了CdrFileMigration
删除列:
public override void Up()
{
CreateTable(
"administration.cdrFiles",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(),
//fileNameWithExtension = c.String(), // <-- I removed this line
url = c.String(),
serviceType = c.String(),
date = c.DateTime(nullable: false),
state = c.Int(nullable: false),
operatorName = c.String(),
acquisitionDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
}
我再次将数据库更新到上次迁移。
数据库已正确创建,但如果我再次运行Add-Migration
命令,则会生成此文件
public partial class aa : DbMigration
{
public override void Up()
{
DropColumn("administration.cdrFiles", "fileNameWithExtension");
}
public override void Down()
{
AddColumn("administration.cdrFiles", "fileNameWithExtension", c => c.String());
}
}
为什么呢?我预计会有空迁移。事实如果我运行此迁移,我得到一个错误:&#34;没有找到要删除的fileNameWithExtension列&#34; ... 有人可以帮帮我吗?
谢谢
答案 0 :(得分:2)
问题是,在将数据库更新到最后一个版本之后,您没有再次运行Add-Migration
。
EF在数据库中保留模型的快照。运行Add-Migration
时会更新此快照。仅返回旧版本并仅编辑旧的迁移文件是不够的。
要解决您的问题,请使用Add-Migration
创建一个空迁移。这将更新数据库中的快照。例如,您只需删除已创建的迁移中的DropColumn
语句,然后Update-Database
即可。如果您再次运行Add-Migration
,则不再生成DropColumn
语句。
总结一下,编辑现有迁移的正确方法是:
Update-Database -TargetMigration {Name of migration before migration to be edited}
Up
和Down
的内容复制到剪贴簿)Add-Migration
再次生成迁移。根据需要进行修改。Update-Database
申请迁移