gpt4 book ai didi

c# - Entity Framework : Dependencies due to foreign key constraints

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:04 26 4
gpt4 key购买 nike

我一直在寻找解决方案,但找不到好的信息。很多 EF 文档已经过时了。这是我的问题。

如果我通过 ParentID 导航属性将 child 添加到 parent ,一切正常。

如果我通过 Children 列表将一个 child 添加到一个父对象,并且这个 child 已经存在,我会得到这个异常:

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

如果我通过 Children 列表将一个子项添加到父项并且该子项是新的(也需要持久化),我会得到这个异常:

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.

节点.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);
}

最佳答案

你试过让你的 child 拥有属性(property)吗

public virtual ICollection<Node>而不是 List<Node>

关于c# - Entity Framework : Dependencies due to foreign key constraints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6588675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com