【发布时间】:2018-08-19 06:20:23
【问题描述】:
我是 EF 的新手。我遇到了创建多对多自引用关系的问题。 我尝试使用以下解决方案:Entity Framework Core: many-to-many relationship with same entity
我的实体:
public class WordEntity
{
public long Id { get; set; }
public string Name { get; set; }
public string Json { get; set; }
public virtual List<WordSinonymEntity> Sinonyms { get; set; }
}
public class WordSinonymEntity
{
public long WordId { get; set; }
public virtual WordEntity Word { get; set; }
public long SinonymId { get; set; }
public virtual WordEntity Sinonym { get; set; }
}
和下一个配置:
modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Sinonym)
.WithMany(p => p.Sinonyms)
.HasForeignKey(pt => pt.SinonymId);
modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Word)
.WithMany(t => t.Sinonyms)
.HasForeignKey(pt => pt.WordId);`
但它会导致下一个异常。
System.InvalidOperationException: '无法在 'WordEntity.Sinonyms' 和 'WordSinonymEntity.Word' 之间创建关系,因为 'WordEntity.Sinonyms' 和 'WordSinonymEntity.Sinonym' 之间已经存在关系。导航属性只能参与单个关系。'
有没有人可以帮助我或者可以建议一些例子来学习? 谢谢。
【问题讨论】:
标签: c# entity-framework entity-framework-core