0

我有一个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; }

    // ...
}

有一个工作正常,但是当我介绍第二个自我引用时,我得到了错误:

无法确定类型“Model.Foo”和“Model.Foo”之间关联的主体端。此关联的主体端必须使用关系流式 API 或数据注释显式配置。

4

1 回答 1

0

固定的!

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

    // ...
}
于 2015-11-20T19:27:54.000 回答