Search code examples
linqasp.net-coreentity-framework-coreasp.net-core-webapi

Entity Framework include() causes json parse error in ASP.NET


this is my Calendar Model which has many to many relation with Category Model:

public class Calendar
{
    ...
    public ICollection<Category> Categories { get; set; } = new List<Category>();
    ...
}
public class Category
{
    ...
    public ICollection<Calendar> Calendars { get; set; } = new List<Calendar>();
    ...
}

and this is in my OnModelCreating method:

modelBuilder.Entity<Calendar>()
    .HasMany(c => c.Categories)
    .WithMany(cc => cc.Calendars);

And this is in my Controller

var query = _context.Calendars.AsNoTracking().AsQueryable();
var calendars = await query.Include(c => c.Categories).ToArrayAsync();
return ok(calendars);

The result errors when browser try parse it to json


Solution

  • The issue you're facing might be related to the circular reference between Calendar and Category entities. When these entities reference each other, serializing them to JSON can cause an infinite loop and result in a stack overflow error.

    To solve this issue, you can use the [JsonIgnore] attribute on the navigation properties that cause the circular reference. This attribute tells the JSON serializer to ignore the specified property during serialization. In your case, you can add the attribute to either Categories in Calendar or Calendars in Category.

    OR

    you can configure the serialization settings to ignore circular references globally in your Startup.cs

    services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        });