How to have two self-references in an entity class

為{幸葍}努か 提交于 2021-01-29 07:25:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!