首页 文章

ALTER TABLE语句与FOREIGN KEY约束冲突

提问于
浏览
7

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

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”,表“dbo.Countries”,列“ID”中 .

4 回答

  • 0

    对于您的Student实体,您可以使用附加到该类型的问号将您的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; }
    }
    
  • 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");
    }
    
  • 3

    我有同样的问题,并使用外键记录截断表,并成功 .

  • 2

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

相关问题