FK error while running Migrations on C#

Asked

Viewed 237 times

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 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 passed by so help me please.

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");
}
  • Can I post the contents of the Migration file? Or are you updating directly, without using explicit migrations?

  • ready updated in question

  • Data already exists in the table Branches, right?

  • yes I already have data in it

  • Well, just see my answer.

1 answer

2


This happens because there are already data in the table dbo.Branches.

See, you’re creating a column obligatory, that is, that it cannot have null value. When creating this column, SQL Server automatically needs to put a value to existing records.

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

Setting the value of this column to zero, it is expected that there is some row at the other end of the relation (in the table dbo.TypeDeliveries) that contains this primary key and that does not exist, so please pop this error.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.