实体框架一对多关系相同类型

本文关键字:同类型 关系 一对多 框架 实体 | 更新日期: 2023-09-27 17:50:52

我试图使用相同类型获得一对多关系。

public class CompanionLinkedCompanion
{
    public int CompanionId { get; set; }
    [ForeignKey("CompanionId")]
    public virtual Companion Companion { get; set; }
    public int LinkedCompanionId { get; set; }
    [ForeignKey("LinkedCompanionId")]
    public virtual Companion LinkedCompanion { get; set; }
}
然后

public class Companion
{
    public virtual ICollection<CompanionLinkedCompanion> CompanionLinkedCompanions { get; set; }
}

当我尝试此操作时,未填充链接同伴的同伴集合。

任何帮助都将不胜感激。

更新修复使用@iraj part-solution:

public class CompanionLinkedCompanion : Entity
{
    public int Id { get; set; }
    public int CompanionId { get; set; }
    [ForeignKey("CompanionId")]
    [InverseProperty("CompanionLinkedCompanions")]
    public virtual Companion Companion { get; set; }
    public int LinkedCompanionId { get; set; }
    [ForeignKey("LinkedCompanionId")]
    public virtual Companion LinkedCompanion { get; set; }
}

实体框架一对多关系相同类型

对于一对多关系,您需要一个标准的父/子关系(只需要一个实体类):

public class Companion
{
    public int CompanionId { get; set; }
    public int? LinkedCompanionId { get; set; }
    [ForeignKey("LinkedCompanionId")]
    // ParentCompanion
    public virtual Companion LinkedCompanion { get; set; }
    [InverseProperty("LinkedCompanion")]
    // ChildrenCompanions
    public virtual ICollection<Companion> CompanionLinkedCompanions { get; set; }
}

use this:

 public class CompanionLinkedCompanion
{
 public int CompanionId { get; set; }
 [ForeignKey("CompanionId")]
 [InverseProperty("CompanionLinkedCompanions")]
 public virtual Companion Companion { get; set; }
 public int LinkedCompanionId { get; set; }
 [ForeignKey("LinkedCompanionId")]
 [InverseProperty("LinkedCompanions")]
 public virtual Companion LinkedCompanion { get; set; }
}

public class Companion
{
  [InverseProperty("Companion")]
  public virtual ICollection<CompanionLinkedCompanion> CompanionLinkedCompanions { get; set; }
  [InverseProperty("LinkedCompanion")]
  public virtual ICollection<CompanionLinkedCompanion> LinkedCompanions { get; set; }
}
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
       modelBuilder.Entity<CompanionLinkedCompanion>().HasRequired(x => x.Companion).WithMany().HasForeignKey(x => x.CompanionId).willCascadeOnDelete(false);
      modelBuilder.Entity<CompanionLinkedCompanion>().HasRequired(x => x.LinkedCompanion).WithMany().HasForeignKey(x => x.LinkedCompanionId);
  }