问题
I want to add a not-null, foreing key column to an existing table.
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 );
Exception message:
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:
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
来源:https://stackoverflow.com/questions/22665416/ef-6-code-based-migration-add-not-null-property-to-existing-entity