我正在访问Microsoft的多对多ef核心示例
https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many
但是会出现自引用循环错误。
这是我的实体:
public class Card
{
public Guid Id { get; set; }
public string CardNumber { get; set; }
public CardType CardType { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int PassCode { get; set; }
public List<CardSet> CardSets { get; set; }
public Card()
{
CardSets = new List<CardSet>();
}
}
public class Set
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<CardSet> CardSets { get; set; }
public Set()
{
CardSets = new List<CardSet>();
}
}
// join entity
public class CardSet
{
public Guid SetId { get; set; }
public Set Set { get; set; }
public Guid CardId { get; set; }
public Card Card { get; set; }
}
这是我的OnModelCreating:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CardSet>().HasKey(cs => new {cs.CardId, cs.SetId});
modelBuilder.Entity<CardSet>()
.HasOne(cs => cs.Card)
.WithMany(c => c.CardSets)
.HasForeignKey(cs => cs.CardId);
modelBuilder.Entity<CardSet>()
.HasOne(cs => cs.Set)
.WithMany(s => s.CardSets)
.HasForeignKey(cs => cs.SetId);
}
以下是通过电话卡获得套装的电话:
public Set GetSetWithCards(Guid setId)
{
return context
.Sets
.Include(s => s.CardSets)
.ThenInclude(cs => cs.Card)
.FirstOrDefault(s => s.Id == setId);
}
错误:
Newtonsoft.Json.JsonSerializationException: Self referencing loop
detected for property 'set' with type
'Tools.Entities.Set'. Path 'cardSets[0]'.
答案 0 :(得分:0)
您所有的实体配置都是正确的,并且根据错误消息,当您尝试将结果数据序列化为JSON时,似乎出现了问题。
查看此答案以获取详细信息:JSON.NET Error Self referencing loop detected for type