【发布时间】:2014-03-26 15:17:21
【问题描述】:
我想在现有表中添加一个非空的外键列。
环境:EF 6,代码优先,基于代码的迁移
//Code from Migration class for new entity Currency
CreateTable("dbo.Currency",
c => new
{
CurrencyID = c.Int(nullable: false, identity: true),
Code = c.String(nullable: false, maxLength: 3, fixedLength: true, unicode: false),
Denomination = c.String(nullable: false, maxLength: 50, unicode: false),
})
.PrimaryKey(t => t.CurrencyID);
AddColumn("dbo.Collection", "CurrencyID", c => c.Int(nullable: false));
//Code from Seed() method in Configuration class
context.Currencies.AddOrUpdate(
new Currency
{
Code = "USD",
Denomination = "Dollar"
}
);
//Here i get an exception. Collection is the existing table
context.Database.ExecuteSqlCommand( "update collection set CurrencyID = 1 );
异常信息:
UPDATE 语句与 FOREIGN KEY 约束冲突 “FK_dbo.Collection_dbo.Currency_CurrencyID”。冲突发生在 表“dbo.Currency”,列“CurrencyID”。
【问题讨论】:
-
我可能只会在 SQL 中创建货币。我猜 AddOrUpdate 没有提交给数据库
-
@Thewads,我认为这会破坏 Code-First 工作流程,我很快就会遇到问题。
-
这么说吧,你的迁移在你的播种机之前运行,所以如果你直到播种机才投入货币,这将不起作用
-
完全是@Thewads,这就是我目前遇到的问题。
-
那么,为什么不直接更新播种机中的收集表呢?还是在播种前将数据放入其中?
标签: entity-framework ef-code-first entity-framework-migrations