Entity Framework The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

Viewed 60664

On updating database in Entity Framework , Code first Migration, I am getting this error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Clients_dbo.MedicalGroups_MedicalGroupId". The conflict occurred in database "hrbc", table "dbo.MedicalGroups", column 'Id'.

This is my class:

public partial class Client
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? MedicalGroupId { get; set; }
    [ForeignKey("MedicalGroupId")]
    public virtual MedicalGroups MedicalGroup { get { return _MedicalGroup; } set { _MedicalGroup = value; } }
}

Here is my 2nd class:

public partial class MedicalGroups
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

And this is my migration which I am trying to apply:

public override void Up()
{
    AddForeignKey("dbo.Clients", "MedicalGroupId", "dbo.MedicalGroups", "Id");
    CreateIndex("dbo.Clients", "MedicalGroupId");
}
13 Answers

This error can also happen if you have orphan records in the child table. Clean up the database should resolve the issue.

I also received this message. The problem was that the test data in the db was incorrect. I didn't have validation on when I was testing and hence i had null values for IDs for fields that do not allow nulls. Once I fixed the data, the update-database command ran successfully.

Had that issue but fortunately I was just building my tables. I only had a couple sample items in each table. Deleted all the rows in both tables then it worked. I'm a noob so take it for what it's worth

You could also use data seeding via

modelBuilder.Entity<MedicalGroups>()
.HasData(new MedicalGroups { ... }, new MedicalGroups { ... })

in your DbContexts class OnModelCreating method.

That way you can insert all the MedicalData rows whos Id is missing from the referencing table. At least in my case the data got seeded bofere it was needed and update-database worked properly.

Related