16

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.

4

2 回答 2

47

不知道是否为时已晚,但我有同样的问题,也许这可以帮助你。

我无法从您的帖子中看到,但您的 TraderUser 表可能已经插入了一些行。您要完成的是创建新表 TraderCompany 并在 TraderUser 中创建指向 TraderCompany 表的外键关系。

在一次迁移中,您尝试为已包含数据的表创建不可为空的外键关系。

您可以尝试以下操作:

  • 第一次迁移 - 一切都一样,除了这条线

    public int TraderCompanyId { get; set; } 
    

    应该

    public int? TraderCompanyId { get; set; }
    

    这将允许您创建可为空的外键列。

  • 使用 TraderCompany 表中的某些行更新您的 TraderCompanyId 列以获取现有数据。

  • 第二次迁移 - 更改代码

    public int? TraderCompanyId { get; set; }
    

    public int TraderCompanyId { get; set; }
    

    并运行您的迁移。

我希望这能帮到您。

于 2013-10-30T20:58:55.770 回答
0

另一种方法是在迁移代码中添加一条 SQL 语句,以便在添加外键之前插入一行。这是我所做的一个例子:

        // 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");
于 2013-11-12T12:00:02.043 回答