我有一个Foo
,可以有两个对自身的可选引用:ParentId
和RootId
。
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或数据注释显式配置此关联的主要结尾。
答案 0 :(得分: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; }
// ...
}