Error in FK when running Migrations in C #

1

I have the following scenario

public class branch()
{
    public Branch()
    {
        Branchs = new HashSet<Branch>();
    }

    [StringLength(80)]
    public string Description { get; set; }

    [Required]
    [ForeignKey("TypeDelivery")]
    public long TypeDeliveryId { get;set; }

    public virtual TypeDelivery TypeDeliverys { get; set; }
}
public class TypeDelivery()
{
    public TypeDelivery()
    {
        Branchs = new HashSet<Branch>();
    }

    [StringLength(80)]
    public string Description { get; set; }
    public virtual ICollection<Branch> Branchs { get; set; }
}

But when I run the update-database on migrations it returns the following error.

  

Error Number: 547, State: 0, Class: 16
      The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Branches_dbo.TypeDeliveries_TypeDeliveryId". The conflict occurred in database "PensouChegouProducao", table "dbo.TypeDeliveries", column 'Id'.

If anyone has been through this please help me.

Follow the migration file.

public override void Up()
{
    AddColumn("dbo.Branches", "TypeDeliveryId", c => c.Long(nullable: false));
    CreateIndex("dbo.Branches", "TypeDeliveryId");
    AddForeignKey("dbo.Branches", "TypeDeliveryId", "dbo.TypeDeliveries", "Id");
}

public override void Down()
{
    DropForeignKey("dbo.Branches", "TypeDeliveryId", "dbo.TypeDeliveries");
    DropIndex("dbo.Branches", new[] { "TypeDeliveryId" });
    DropColumn("dbo.Branches", "TypeDeliveryId");
}
    
asked by anonymous 19.06.2017 / 18:58

1 answer

2

This happens because data already exists in the dbo.Branches table.

You see, you are creating a mandatory column, that is, it can not have a null value. When creating this column, SQL Server automatically needs to put a value for the existing records.

And what is the default value for a numeric column? That's right, zero, nihil .

By putting the value of this column to zero, it is expected that there will be some line at the other end of the relationship (in the dbo.TypeDeliveries table) that contains this primary key and that does not exist, this error.

Clear the table before running migration or set a default value for the column.

    
19.06.2017 / 19:23