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"); }
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.
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.
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.
Check that there is not existing data in the database that is conflicting with the FK constraint causing the creation to fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With