skip to content

Why does returning an EF Core entity with back-references from an ASP.NET Core 10 controller throw a JsonException, and how do you fix it?

level: middleimportance: should knowfreq 45%

answer

  1. navigation points back to its parent
  2. serializer follows every loaded reference
  3. MaxDepth 32 in MVC's JsonOptions
  4. ReferenceHandler.IgnoreCycles vs Preserve
  5. a response DTO has no cycle

basics

~10 s

System.Text.Json follows navigation properties, so Shipment.Parcels[0].Shipment loops until the depth limit (32 in MVC) and throws a JsonException. Return a DTO without back-references, or set ReferenceHandler.IgnoreCycles or Preserve in the JSON options.

solid answer

~40 s

An EF Core entity graph is often cyclic: a `Shipment` has `Parcels`, and each `Parcel` has a `Shipment` navigation back. System.Text.Json has no cycle handling by default, so it walks `shipment.parcels[0].shipment.parcels...` until it passes `MaxDepth`, which MVC's `JsonOptions` sets to 32, and throws a `JsonException`. The cycle exists only where navigations were loaded, by `Include` or by fix-up of entities already tracked. The best fix is a response DTO or a `Select` projection that has no back-reference. If you must serialize entities, `ReferenceHandler.IgnoreCycles` writes `null` where a reference repeats, and `ReferenceHandler.Preserve` emits `$id` / `$ref` metadata that clients must understand. `[JsonIgnore]` on the back-reference also works but hides the property from every serialization.

code

csharp · 20 lines
csharp
[ApiController]
[Route("api/shipments")]
public class ShipmentsController(ShippingDb db) : ControllerBase
{
    [HttpGet("{id:int}")]
    public async Task<ActionResult<ShipmentDto>> Get(int id, CancellationToken ct)
    {
        var dto = await db.Shipments
            .Where(s => s.Id == id)
            .Select(s => new ShipmentDto(
                s.Id,
                s.Parcels.Select(p => new ParcelDto(p.Id, p.WeightGrams)).ToList()))
            .SingleOrDefaultAsync(ct);

        return dto is null ? NotFound() : dto;
    }
}

public record ShipmentDto(int Id, List<ParcelDto> Parcels);
public record ParcelDto(int Id, int WeightGrams);

go deeper

for a junior

Recall that entities with two-way navigations can make serialization loop and that returning a DTO avoids it.

for a middle

Explain how fix-up creates the loop, why MaxDepth 32 is where MVC fails, and how IgnoreCycles and Preserve differ in output.

for a senior

Push for DTO projections over serializing entities, and weigh the client cost of Preserve metadata or ambiguous nulls from IgnoreCycles.

for a principal

Set the rule that persistence entities never cross the API boundary, so cycles, over-fetching and leaked fields are designed out.

## Where the cycle comes from In the shipping-label service, `Shipment` and `Parcel` are EF Core entities with a two-way relationship: ```csharp public class Shipment { public int Id { get; set; } public List<Parcel> Parcels { get; set; } = []; } public class Parcel { public int Id { get; set; } public int ShipmentId { get; set; } public int WeightGrams { get; set; } public Shipment Shipment { get; set; } = null!; } ``` After `db.Shipments.Include(s => s.Parcels)`, EF Core's relationship fix-up sets each `Parcel.Shipment` to the same `Shipment` instance. The object graph now contains a loop. ## Why serialization fails System.Text.Json serializes public properties recursively. By default it **does not track references**, so it cannot tell that `parcel.Shipment` is the object it started from. It keeps descending until the depth passes `MaxDepth`: - MVC's `Microsoft.AspNetCore.Mvc.JsonOptions` sets `MaxDepth` to **32**. - Minimal APIs use the serializer's own default limit. Past the limit the serializer throws a `JsonException` whose message points at a possible object cycle or an over-deep graph, and the request fails with a 500. If part of the body was already flushed, the client may instead see a truncated response. ## The fixes, from best to most invasive 1. **Return a DTO.** Map the entity to a response type that holds what the client needs and no back-reference. A LINQ `Select` projection also avoids loading columns you never send. This is the fix most reviewers expect, because it also stops leaking internal fields. 2. **`ReferenceHandler.IgnoreCycles`.** Set in the JSON options; when the serializer meets an object already on the current path, it writes `null` instead of recursing. The JSON stays plain, but the `null` can be mistaken for "no shipment". 3. **`ReferenceHandler.Preserve`.** Every object gets an `$id`, repeats become `{"$ref": "1"}`, and collections are wrapped in `$values`. Cycles round-trip exactly, but every client must understand the metadata. 4. **`[JsonIgnore]` on the back-reference.** Simple and explicit, but it hides `Parcel.Shipment` from every serialization of that type, including places where you wanted it. | Option | JSON shape | Who must change | |---|---|---| | DTO / projection | plain, minimal | the server's mapping code | | `IgnoreCycles` | plain, with `null` at the loop | nobody, but `null` is ambiguous | | `Preserve` | `$id`, `$ref`, `$values` metadata | every client | | `[JsonIgnore]` | plain, property always absent | the entity class | ## Configuring a reference handler It goes into the JSON options of the stack that serializes the response: ```csharp builder.Services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles); ``` Minimal API endpoints need the same setting through `ConfigureHttpJsonOptions` on `o.SerializerOptions`. ## How it shows up - The exception surfaces in the application log for the request, raised from the output formatter while it writes the response, not from your action code. - The action itself returns normally, so a debugger breakpoint inside the action shows a perfectly good object. - The failure appears only for shipments that actually have parcels loaded; an empty list has nothing to recurse into, which makes the bug look intermittent. ## Choosing in practice Most teams treat the cycle as a symptom: the API is exposing persistence types. Moving to response DTOs fixes the cycle, stops over-posting and over-sharing, and decouples the JSON contract from the database schema. `IgnoreCycles` is a reasonable stop-gap for an internal endpoint, while `Preserve` fits best when both ends are .NET code that deserializes with the same handler. ## Related traps - **Lazy loading:** with lazy-loading proxies, the serializer touches every navigation and triggers a query for each one while writing the response, which is slow even without a cycle. - **Raising MaxDepth** only delays the exception for a real cycle; it is the right knob only for legitimately deep, acyclic data. - **Newtonsoft history:** apps on `AddNewtonsoftJson` used `ReferenceLoopHandling.Ignore` for the same problem; the System.Text.Json equivalent is `ReferenceHandler.IgnoreCycles`.

  • What does a client receive for the Parcel.Shipment property under ReferenceHandler.IgnoreCycles?
    `null`. When the serializer meets an object that is already on the current serialization path, `IgnoreCycles` writes `null` instead of recursing. The JSON is valid and plain, but a client cannot tell that `null` from a parcel with no shipment, which is one reason a DTO is usually preferred.
  • Why is raising MaxDepth not a fix for this exception?
    A cycle is infinite, so any depth limit is eventually exceeded; raising `MaxDepth` only makes the serializer do more work before it throws. Raise it only when the data is legitimately deep and acyclic, and keep in mind that the limit also protects the server from hostile, deeply nested request bodies.

  • System.Text.Json detects cycles automatically and skips repeated objects.
  • Raising MaxDepth to a large value fixes a reference cycle.
  • ReferenceHandler.Preserve writes plain JSON that any client can read unchanged.
  • EF Core navigations are never serialized unless marked with an attribute.
  • The cycle appears even when the navigation property was never loaded.