'EF Migrations: The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I had these classes

public class Bid : ...
{
   ...

   [Required]
   public virtual TraderUser Trader { get; set; }
}

public class TraderUser : ...
{
   ...
}

I then changed these classes in the following way and added a new class

public class Bid : ...
{
   ...

   [Required]
   public virtual TraderUser TraderUser { get; set; }
}

public class TraderUser : ...
{
   ...

   public int TraderCompanyId { get; set; }

   [ForeignKey("TraderCompanyId")]
   public virtual TraderCompany TraderCompany { get; set; }
}

public class TraderCompany : ...
{
   ...
}

When I did an update-database I got the following error

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Bid_dbo.TraderUser_TraderUser_Id". The conflict occurred in database "LeasePlan.Development", table "dbo.TraderUser", column 'Id'.

I can't get the database to update. Any help is much appreciated.



Solution 1:[1]

The alternative is to add an SQL statement within the migration code to insert a row before it adds the foreign keys. Here's an example of what I did:

        // Countries is a new table
        CreateTable(
            "dbo.Countries",
            c => new
                {
                    CountryID = c.Int(nullable: false, identity: true),
                    Name = c.String(),
                    Currency = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.CountryID);
        // Heres where i insert a row into countries
        Sql("INSERT INTO Countries (Name, Currency) VALUES ('United Kingdom', 0)");
        // I set the default value to 1 on the ID fields
        AddColumn("dbo.Brokers", "CountryID", c => c.Int(nullable: false, defaultValue: 1));
        AddColumn("dbo.Products", "CountryID", c => c.Int(nullable: false, defaultValue: 1));
        AddForeignKey("dbo.Brokers", "CountryID", "dbo.Countries", "CountryID", cascadeDelete: false);
        AddForeignKey("dbo.Products", "CountryID", "dbo.Countries", "CountryID", cascadeDelete: false);
        // Migrations then creates index's
        CreateIndex("dbo.Brokers", "CountryID");
        CreateIndex("dbo.Products", "CountryID");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 itaylorweb