Search code examples
c#join.net-coreentity-framework-coremany-to-many

Entity Framework Core 2.2 Many-to-Many Self Reference Loop


I am following Microsoft's many-to-many ef core example at

https://learn.microsoft.com/en-us/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:

    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]'.

Solution

  • 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.

    Check out this answer for details: JSON.NET Error Self referencing loop detected for type