开发者

Entity Framework: Dependencies due to foreign key constraints

开发者 https://www.devze.com 2023-03-18 17:53 出处:网络
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.

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


Have you tried making your Children property

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消