Avoid or control circular references in Entity Framework Core

Assuming you are using the latest and greatest ASP .NET Core 3.1 with System.Text.Json, to handle reference loops you will need to switch “back” to Newtonsoft.Json (though it worth mentioning that System.Text.Json should be faster. Also support for reference loops handling is coming, as @Eric J. wrote in comments):

services.AddControllers()
    .AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)

As for EF creating reference loops – it is called relationship fixup and you can’t do a lot about it (see this answer). AsNoTracking can help a little bit (but not in case of Include). My personal approach is to return DTO’s from endpoints and not entites directly.

UPD

In .NET 5.0 ReferenceHandler is introduced, so next should do the trick:

services.AddControllersWithViews()
    .AddJsonOptions(options =>
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve)

Leave a Comment