使用实体框架核心2.2.4如何与同一表中的“一对多”关系?我用流利的api建立外键关系
public class Animal
{
[Key]
public string AnimalId { get; set; }
public int CategoryId { get; set; }
public DateTime BirthDate { get; set; }
public string FatherId { get; set; }
public string MotherId { get; set; }
public int GenotypeId { get; set; }
#region Foreign Key
public Genotype Genotype { get; set; }
public ICollection<Animal> Animals { get; set; }
public Animal FatherAnimal{ get; set; }
public Animal MotherAnimal{ get; set; }
public AnimalCategory AnimalCategory { get; set; }
#endregion
}
Fluent API:
builder.HasOne<Animal>(s => s.FatherAnimal)
.WithMany(a => a.Animals)
.HasForeignKey(s => s.FatherId ).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<Animal>(s => s.MotherAnimal)
.WithMany(a => a.Animals)
.HasForeignKey(s => s.MotherId ).OnDelete(DeleteBehavior.Cascade);
无法在“ Animal.Animals”和“ Animal.MotherAnimal”之间创建关系,因为“ Animal.Animals”和“ Animal.FatherAnimal”之间已经存在关系。导航属性只能参与单个关系。