gpt4 book ai didi

entity-framework - EF 6 基于代码的迁移 : Add not null property to existing entity

转载 作者:行者123 更新时间:2023-12-01 10:49:04 25 4
gpt4 key购买 nike

我想向现有表添加一个非空的外键列。

Environment: EF 6,Code-First, Code-Based Migration

//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 );

异常信息:

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Collection_dbo.Currency_CurrencyID". The conflict occurred in table "dbo.Currency", column 'CurrencyID'.

最佳答案

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

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

关于entity-framework - EF 6 基于代码的迁移 : Add not null property to existing entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22665416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com