EF 7 : INSERT statement conflicted with the FOREIGN KEY SAME TABLE

asp.net-mvc c# entity-framework entity-framework-core sql-server

Question

I have an exception when I call SaveChangesAsync. My architecture is really simple, i have a Category class, wich contains

public class Category {
  public Guid ID {get; set;}
  public Guid? ParentId {get; set;}
  public Category Parent {get; set;}
 [...]
}

When I want to insert a new category in database (connected to my ASP MVC application), I set the GUID before doing the insert. The error occured when my database is empty and I want to insert parent category (so with a null Guid IdParent and null Parent). This is NOT happening if I set a parent value. I can add a record manually by setting parent to Null by Visual studio.

I have the following error :

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Category_Category_ParentId". The conflict occurred in database "HT_Root", table "dbo.Category", column 'ID'. The statement has been terminated.

I searched on stack overflow for a simple answer, and not found it. I try with Fluent API :

modelBuilder.Entity<Category>().HasOne(s => s.Parent).WithMany().HasForeignKey(s => s.ParentId);

But nothing changed. What am I doing wrong ?

Accepted Answer

It seems to have changed in EF 7 See this github issue

Try

public class Category 
{
    public Guid ID {get; set;}
    public Guid? ParentId {get; set;}
    public Category Parent {get; set;}
    public ICollection<Categories> Children {get; set;}
}

And

modelBuilder.Entity<Category>()
    .HasOne(x => x.Parent)
    .WithMany(x => x.Children)
    .HasForeignKey(x => x.ParentId)
    .Required(false);

You should also always check that (if specified) the ParentId exists in the database. Watch out for adding Guid.Empty (00000000-0000-0000-0000-000000000000) instead of null as this can cause issues.



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why