EF 6基于代码的迁移:向现有实体添加非null属性 [英] EF 6 Code-Based Migration: Add not null property to existing entity
本文介绍了EF 6基于代码的迁移:向现有实体添加非null属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在现有表中添加非空的前导键列。
I want to add a not-null, foreing key column to an existing table.
环境:EF 6,Code-First ,基于代码的迁移
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 );
异常消息:
UPDATE语句与FOREIGN KEY约束
FK_dbo.Collection_dbo.Currency_CurrencyID冲突。
表 dbo.Currency的 CurrencyID列中发生冲突。
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Collection_dbo.Currency_CurrencyID". The conflict occurred in table "dbo.Currency", column 'CurrencyID'.
推荐答案
问题已解决,这里按顺序执行我遵循的步骤:
Problem solved, here are enumerated by order the steps i followed:
- 将外键属性映射更改为不需要
- 仅种子主键值
- 更新数据库
- 将属性改回必需
- 添加新的迁移并为外键列的值填充
- 更新数据库
- Change the foreign key property mapping to Not Required
- Seed only the primary key values
- Update-Database
- Change back the property to Required
- Add new migration and seed the values for foreign key column
- Update-Database
这篇关于EF 6基于代码的迁移:向现有实体添加非null属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文