Entity framework 如何在实体类中有两个自引用
我有一个Entity framework 如何在实体类中有两个自引用,entity-framework,asp.net-web-api-odata,Entity Framework,Asp.net Web Api Odata,我有一个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 { ge
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”之间关联的主体端。必须使用关系fluent API或数据注释显式配置此关联的主体端
修正
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();
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; }
// ...
}