Search code examples
c#sql.netsql-serverentity-framework

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");
}

Solution

  • I got the solution of my Problem. Problem is "data" which i have in my clients table. Because my client table have medicalgroupid values which are not actually exist that's why it is giving me error on foreign key constraint.

    Update Client set MedicalGroupId = NULL