【问题标题】:EF 6 Code-Based Migration: Add not null property to existing entityEF 6 基于代码的迁移:向现有实体添加非空属性
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多