如何在一个实体中有两个自引用 class

How to have two self-references in an entity class

我有一个 Foo,它可以有两个可选的对自身的引用:ParentIdRootId

public class Foo
{
    [Key]
    public int FooId { get; set; }

    public int? ParentId { get; set; }

    [ForeignKey(nameof(ParentId))]
    public virtual Foo Parent { get; set; }

    public int? RootId { get; set; }

    [ForeignKey(nameof(RootId))]
    public virtual Foo RootFoo { get; set; }

    // ...
}

有一个工作正常,但是当我引入第二个自我引用时出现错误:

Unable to determine the principal end of an association between the types 'Model.Foo' and 'Model.Foo'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

已修复!

EF 想知道 Foo 另一边的关系是什么样的,即:

Foo has one Parent / but a Parent, how many Foos has?
Foo has one RootFoo / but a RootFoo, how many Foos has?

使用 Fluet API:

var foo = modelBuilder.Entity<Foo>().ToTable("Foo", schemaName);
foo.HasOptional(a => a.Parent).WithMany();
foo.HasOptional(a => a.RootFoo).WithMany();

或使用InverseProperty注解:

public class Foo
{
    [Key]
    public int FooId { get; set; }

    public int? ParentId { get; set; }

    [ForeignKey(nameof(ParentId))]
    public virtual Foo Parent { get; set; }

    [InverseProperty("Parent")]
    public virtual ICollection<Foo> SingleLevelChildren { get; set; }

    public int? RootFooId { get; set; }

    [ForeignKey(nameof(RootFooId))]
    public virtual Foo RootFoo { get; set; }

    [InverseProperty("RootFoo")]
    public virtual ICollection<Foo> AllChildren { get; set; }

    // ...
}