2
votes

I have been looking around for a solution and cannot find good information. A lot of EF documentation is very out of date. Here is my problem.

If I add a child to a parent via the ParentID navigation property, everything works fine.

If I add a child to a parent via the Children list and the child is pre-existing, I get this exception:

DbUpdateException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

If I add a child to a parent via the Children list and the child is new (also needs to be persisted), I get this exception:

DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

Node.cs

public class Node
{
  public long ID { get; private set; }
  public long? ParentID { get; set; }
  public List<Node> Children { get; set; }
}

Relevant DbContext.cs

protected override void OnModelCreating(DbModelBuilder mb)
{
  mb.Entity<Node>()
    .HasMany(c => c.Children)
    .WithOptional()
    .HasForeignKey(c => c.ParentID);
}
2

2 Answers

0
votes

Have you tried making your Children property

public virtual ICollection<Node> instead of a List<Node>

0
votes

I had the same issue, not sure what is the best solution but i tried to call SaveChanges. context.SaveChanges() and then Add the Child to Newly Created Entity and it worked.