Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"); } 
like image 521
Zaid Iqbal Avatar asked Jan 01 '14 17:01

Zaid Iqbal


People also ask

How do you fix the alter table statement conflicted with the foreign key constraint?

You can use With NoCheck with alter table statement and it will ignore the check to validate data and create Foreign Key Constraint. Once the Foreign Key Constraint will be created, it will enforce integrity for any new records inserted.

How do I get rid of migration EF core?

Delete your Migrations folder. Create a new migration and generate a SQL script for it. In your database, delete all rows from the migrations history table. Insert a single row into the migrations history, to record that the first migration has already been applied, since your tables are already there.

What is foreign key w3schools?

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.


1 Answers

Check that there is not existing data in the database that is conflicting with the FK constraint causing the creation to fail.

like image 93
Turnkey Avatar answered Sep 22 '22 21:09

Turnkey