EF 6基于代码的迁移:向现有实体添加非null属性

E-B*_*Bat 3 entity-framework ef-code-first ef-migrations

我想在现有表中添加一个非null,foreing键列.

环境: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 ); 
Run Code Online (Sandbox Code Playgroud)

异常消息:

UPDATE语句与FOREIGN KEY约束"FK_dbo.Collection_dbo.Currency_CurrencyID"冲突.冲突发生在表"dbo.Currency",列'CurrencyID'中.

E-B*_*Bat 6

问题解决了,这里按顺序列举我遵循的步骤:

  1. 将外键属性映射更改为"不需要"
  2. 仅种子主键值
  3. 更新数据库
  4. 将属性更改为Required
  5. 添加新迁移并为外键列设置种子值
  6. 更新数据库