实体框架:由于外键约束而产生的依赖关系
我一直在寻找解决方案,但找不到好的信息。很多 EF 文档都已经过时了。这是我的问题。
如果我通过 ParentID 导航属性将子项添加到父项,则一切正常。
如果我通过“子项”列表将一个子项添加到父项,并且该子项已存在,则会出现以下异常:
DbUpdateException:无法确定 受抚养人的有效订单 运营。由于可能存在依赖关系 外键约束、模型 要求,或商店生成的 值。
如果我通过“子项”列表将一个子项添加到父项,并且该子项是新的(也需要保留),则会出现以下异常:
DbUpdateConcurrencyException:存储 更新、插入或删除语句 影响了意外数量的行 (0)。实体可能已被修改 或在实体加载后被删除。 刷新 ObjectStateManager 条目。
Node.cs
public class Node
{
public long ID { get; private set; }
public long? ParentID { get; set; }
public List<Node> Children { get; set; }
}
相关DbContext.cs
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<Node>()
.HasMany(c => c.Children)
.WithOptional()
.HasForeignKey(c => c.ParentID);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过将 Children 属性设置
为
public virtual ICollection
而不是List
Have you tried making your Children property
public virtual ICollection<Node>
instead of aList<Node>
我遇到了同样的问题,不确定最好的解决方案是什么,但我尝试调用 SaveChanges。 context.SaveChanges() 然后将子添加到新创建的实体中并且它起作用了。
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.