简体   繁体   中英

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

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM