到根实体的树的每个节点上是否可以具有导航属性?

考虑以下模型:

public class Node
{
    public int Id { get; set; }
    public int? ParentNodeId { get; set; }
    public Node ParentNode { get; set; }
}

Is it possible to add another navigational property which would link to the root node object (the one where ParentNodeId == null)?

我试过了,但是没有用:

public class Node
{
    public int Id { get; set; }
    public int? ParentNodeId { get; set; }
    public Node ParentNode { get; set; }
    public int RootNodeId { get; set; }
    public Node RootNode { get; set; }
}

modelBuilder.Entity<Node>()
    .HasOne(m => m.RootNode)
    .WithOne(a => a.RootNode)
    .HasForeignKey<Node>(k => k.RootNodeId).OnDelete(DeleteBehavior.NoAction);

迁移错误消息:

无法将属性或导航“ RootNode”添加到实体类型“节点”,因为在实体类型“节点”上已经存在具有相同名称的属性或导航。

更新资料

我在这里尝试一下。这是这样做的方式吗?

public class Node
{
    public int Id { get; set; }
    public int? ParentNodeId { get; set; }
    public Node ParentNode { get; set; }
    public List<Node> DescendantNodes { get; set; }
    public int RootNodeId { get; set; }
    public Node RootNode { get; set; }
}

modelBuilder.Entity<Node>()
    .HasOne(m => m.RootNode)
    .WithMany(a => a.DescendantNodes)
    .HasForeignKey(k => k.RootNodeId).OnDelete(DeleteBehavior.NoAction);
评论