简体   繁体   English

实体框架核心2.2多对多自引用循环

[英]Entity Framework Core 2.2 Many-to-Many Self Reference Loop

I am following Microsoft's many-to-many ef core example at 我在下面关注Microsoft的多对多ef核心示例

https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many https://docs.microsoft.com/zh-cn/ef/core/modeling/relationships#many-to-many

But get a self referencing loop error. 但是会出现一个自引用循环错误。

Here are my entities: 这是我的实体:

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; }
}

Here is my OnModelCreating: 这是我的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);
    }

Here is the call to get the Set with its Cards: 这是获取带有卡套的电话:

    public Set GetSetWithCards(Guid setId)
    {
        return context
               .Sets
               .Include(s => s.CardSets)
               .ThenInclude(cs => cs.Card)
               .FirstOrDefault(s => s.Id == setId);
    }

The error: 错误:

 Newtonsoft.Json.JsonSerializationException: Self referencing loop
 detected for property 'set' with type
 'Tools.Entities.Set'. Path 'cardSets[0]'.

All of your entity configurations are correct, and, based on the error message, it appears that the issue is happening when you try to serialize the resulting data to JSON. 您所有的实体配置都是正确的,并且根据错误消息,当您尝试将结果数据序列化为JSON时,似乎出现了问题。

Check out this answer for details: JSON.NET Error Self referencing loop detected for type 查看此答案以获取详细信息: JSON.NET错误检测到类型的自引用循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM