问题
I have a Foo
that can have two optional references to itself: ParentId
and 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; }
// ...
}
Having one works fine, but when I introduce the second self-reference I get error:
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.
回答1:
Fixed!
EF wants to know how the relations look like from the other side of Foo, i.e.:
Foo has one Parent / but a Parent, how many Foos has?
Foo has one RootFoo / but a RootFoo, how many Foos has?
With Fluet API:
var foo = modelBuilder.Entity<Foo>().ToTable("Foo", schemaName);
foo.HasOptional(a => a.Parent).WithMany();
foo.HasOptional(a => a.RootFoo).WithMany();
Or using InverseProperty
annotations:
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; }
// ...
}
来源:https://stackoverflow.com/questions/33834242/how-to-have-two-self-references-in-an-entity-class