ALTER TABLE语句与FOREIGN KEY约束冲突

时间:2014-10-11 21:02:50

标签: sql-server entity-framework ef-migrations

当我运行以下迁移时,我收到以下错误:

  

ALTER TABLE语句与FOREIGN KEY约束冲突

我有一个现有的数据库并重构模型以包含导航属性。

查看原始模型,然后查看新模型:

原型:

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

新模式:

public class Student
{
     public int ID { get; set; }
     public string Name { get; set; }
     public int CountryID { get; set; }
     public virtual Country Country { get; set; }
}

public class Country 
{
     public int ID { get; set; }            
     public string Country { get; set; }
}

Add-Migration导航属性:

public override void Up()
{
            CreateTable(
                "dbo.Countries",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        CountryName = c.String(),
                    })
                .PrimaryKey(t => t.ID);

            AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: false));
            CreateIndex("dbo.Students", "CountryID");
            AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true);
            DropColumn("dbo.Students", "Country");
}

Update-Database错误:

  

System.Data.SqlClient.SqlException(0x80131904):ALTER TABLE语句与FOREIGN KEY约束冲突" FK_dbo.Students_dbo.Countries_CountryID"。冲突发生在数据库" aspnet-navprop-20141009041805",table" dbo.Countries",column' ID'。

4 个答案:

答案 0 :(得分:5)

我遇到了同样的问题,我的表有数据,因此我将外键列更改为可空。

AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: true));

您应该像那样更改代码,然后再次运行Update-Database -Verbose

public override void Up()
{
            CreateTable(
                "dbo.Countries",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        CountryName = c.String(),
                    })
                .PrimaryKey(t => t.ID);

            AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: true));
            CreateIndex("dbo.Students", "CountryID");
            AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true);
            DropColumn("dbo.Students", "Country");
}

答案 1 :(得分:3)

我遇到了同样的问题,并使用外键记录截断了表,并且成功了。

答案 2 :(得分:2)

如果表格中有数据(学生表)删除它们,然后重新尝试。

答案 3 :(得分:0)

对于您的学生实体,您可以使用附加在该类型上的问号将您的CountryId属性标记为可为空,即

public class Student
{
     public int ID { get; set; }
     public string Name { get; set; }
     public int? CountryID { get; set; }
     public virtual Country Country { get; set; }
}