EF Core self referencing not working if there are 2 foreign keys to self (Code first)

会有一股神秘感。 提交于 2019-12-05 19:20:45
Steve Greene

I prefer the fluent code for this stuff:

modelBuilder.Entity<DbPart>()
    .HasOne(p => p.Source)
    .WithMany(p => p.SourceParts)
    .HasForeignKey(p => p.SourceId);

modelBuilder.Entity<DbPart>()
    .HasOne(p => p.SourceFake)
    .WithMany(p => p.SourceFakeParts)
    .HasForeignKey(p => p.SourceFakeId);

But if you want annotations try this:

public class DbPart 
{
    public int Id { get; set; }   // Key & Indentity by convention

    public int? SourceId { get; set; }  // FK by convention
    [InverseProperty("SourceParts")]
    public DbPart Source { get; set; }

    public int? SourceFakeId { get; set; } // FK by convention
    [InverseProperty("SourceFakeParts")]
    public DbPart SourceFake { get; set; }

    [InverseProperty("SourceFake")]
    public List<DbPart> SourceFakeParts { get; set; }

    [InverseProperty("Source")]
    public List<DbPart> SourceParts { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!