2014-10-11 313 views
6

当我运行下面的迁移,我收到以下错误:ALTER TABLE语句冲突与外键约束

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

我有一个现有的数据库和重构的模式,包括导航属性。

查看原始模型,然后将新的模式:

原始模型:

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): The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Students_dbo.Countries_CountryID". The conflict occurred in database "aspnet-navprop-20141009041805", table "dbo.Countries", column 'ID'.

+0

为什么这个问题被否决?我认为这个问题是有据可查的。 – 2014-10-12 20:51:06

回答

3

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

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

你应该改变你的代码一样,然后再跑更新数据库-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"); 
} 
3

我有同样的问题,并与外键记录截断表,它成功了。

2

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

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; } 
}