Question

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'.

Was it helpful?

Solution

Problem solved, here are enumerated by order the steps i followed:

  1. Change the foreign key property mapping to Not Required
  2. Seed only the primary key values
  3. Update-Database
  4. Change back the property to Required
  5. Add new migration and seed the values for foreign key column
  6. Update-Database
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top