Covers diagnosing lazy-loading N+1 queries and serialisation cycles in an ASP.NET Core API with EF Core: SQL logging, Application Insights, the System.Text.Json cycle error, and fixing with DTO projection, explicit loading strategy and turning lazy loading off.
Both symptoms come from serialising lazy-loading entities. System.Text.Json reads every public property; each virtual navigation triggers a SQL query on first access (N+1), and back-references such as Order.Customer.Orders form a cycle, so the serialiser throws ("A possible object cycle was detected") or goes very deep.
I diagnose by counting SQL commands per request (EF Core command logging or Application Insights dependencies), then fix it properly: project to a DTO with Select so the response shape is explicit and EF Core sends one query, and turn lazy loading off (or make lazy loads throw) so it can't come back.
Setting ReferenceHandler.IgnoreCycles stops the exception but leaves the dozens of queries in place.
"When I see a JSON cycle error and a high query count on the same endpoint, I suspect the controller is returning EF Core entities with lazy loading on. The proxy overrides each
virtualnavigation getter so that the first read runs a query. The serialiser reads every public property, so serialising 50 orders touchesorder.Customer, thencustomer.Orders, then each of those orders'Lines, and so on. That's one query per navigation per entity, and becauseCustomer.Orderspoints back to orders,System.Text.Jsoneither detects the cycle and throws, or walks until it hits the max depth of 64.For example, at [company] our [order history endpoint] started timing out after someone added a
Customer.Ordersnavigation for another feature. To diagnose, I turned onMicrosoft.EntityFrameworkCore.Database.Commandlogging locally and counted [~150] commands for one request; in Application Insights the end-to-end transaction view showed the same fan-out of SQL dependencies. I put a breakpoint in a smallDbCommandInterceptorthat counted commands, and the stack traces all went through the JSON serialiser into the proxy getters.The quick fix people reach for is
ReferenceHandler.IgnoreCycles. It stops the exception, but the queries still run and the payload still leaks fields like internal notes. The real fix was a DTO projection withSelect, so EF Core generated one query with exactly the fields the client needed, and then turning lazy loading off for the API context so a future navigation can't do the same. [p95 went from ~2.5 s to ~80 ms.] My rule: an API should never serialise entities."
| Step | Tool | What you look for |
|---|---|---|
| 1 | EF Core command logging (LogTo, log category Database.Command) |
Many near-identical SELECT ... WHERE [Id] = @p |
| 2 | Application Insights transaction view | Dozens of SQL dependencies under one request |
| 3 | DbCommandInterceptor counter or MiniProfiler |
Exact command count per request |
| 4 | Stack trace at a command | Proxy getter called from System.Text.Json |
| 5 | Exception message | JsonException: A possible object cycle was detected |
| Option | Fixes N+1 | Fixes cycle | Recommended |
|---|---|---|---|
ReferenceHandler.IgnoreCycles |
No | Yes (drops the back-reference) | Only as a stopgap |
[JsonIgnore] on navigations |
Partly | Yes | No: couples entities to JSON |
Include the needed navigations |
Yes | No | Not for API responses |
DTO projection with Select |
Yes | Yes | Yes |
| Turn lazy loading off | Prevents recurrence | n/a | Yes |
After one navigation was added, an order history endpoint went from [3] to [~150] queries per request and p95 rose to [~2.5 s]. Projecting to a DTO and disabling lazy loading brought it to [1 query and ~80 ms], and the response stopped exposing [internal customer notes].
Checks that the candidate can trace a symptom to lazy loading plus serialisation and fixes the cause, not the exception.
Green flags
IgnoreCycles as hiding the problem.Red flags
[JsonIgnore] or IgnoreCycles.Include everything and keep returning entities.UseLazyLoadingProxies()
└ at model build: Castle DynamicProxy creates OrderProxy : Order
override Customer { get { _loader.Load(this, "Customer"); return base.Customer; } }
first access -> ILazyLoader.Load -> SELECT ... WHERE [c].[Id] = @id
later access -> IsLoaded == true -> no query
The loader needs the context that materialised the entity. After the scope ends you get an exception (or a warning, depending on configuration) instead.
JsonSerializer.Serialize(orders)
for each order:
write Id, Number ...
read order.Customer -> query #1
write customer fields
read customer.Orders -> query #2 (all orders of that customer)
for each of those orders: read order.Customer -> already loaded -> CYCLE
read order.Lines -> query #3
for each line: read line.Product -> query #4..n
System.Text.Json defaults to throwing on a cycle (ReferenceHandler null, MaxDepth 64). Newtonsoft.Json had ReferenceLoopHandling.Ignore, which is why older projects hid this for years.
options.ConfigureWarnings(w => w.Throw(CoreEventId.LazyLoadOnDisposedContextWarning));
// In tests, count commands with an interceptor and assert an upper bound.
You can also stop lazy loading per context instance with db.ChangeTracker.LazyLoadingEnabled = false.
Select(o => new OrderDto(o.Id, o.Number, o.Customer.Name, o.Lines.Count()))
-> one SQL statement, joins and subqueries
-> result objects have no navigations, so no proxies and no cycles
-> the API contract no longer changes when the entity model changes
List<Order> from a controller and count commands in the log.Customer.Orders navigation and reproduce the JsonException.ReferenceHandler.IgnoreCycles and confirm the query count is unchanged.DbCommandInterceptor that counts commands per request and logs it.Before: entities with lazy loading. After: DTO projection, lazy loading off, and a command-count test.
// BEFORE: every navigation the serialiser touches is a query; Customer.Orders creates a cycle.
[HttpGet("customers/{id:int}/orders")]
public async Task<List<Order>> GetOrders(int id, CancellationToken ct) =>
await db.Orders.Where(o => o.CustomerId == id).ToListAsync(ct);
namespace Shop.Api.Orders;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
public sealed record OrderLineDto(string Product, int Quantity, decimal UnitPrice);
public sealed record OrderDto(int Id, string Number, string CustomerName, IReadOnlyList<OrderLineDto> Lines);
[ApiController]
[Route("customers/{id:int}/orders")]
public sealed class CustomerOrdersController(ShopDbContext db) : ControllerBase
{
// AFTER: explicit shape, one SQL statement, nothing lazy, no cycle.
[HttpGet]
public async Task<IReadOnlyList<OrderDto>> Get(int id, CancellationToken ct) =>
await db.Orders
.Where(o => o.CustomerId == id)
.OrderByDescending(o => o.PlacedAt)
.Select(o => new OrderDto(
o.Id,
o.Number,
o.Customer.Name,
o.Lines.Select(l => new OrderLineDto(l.Product.Name, l.Quantity, l.UnitPrice)).ToList()))
.Take(50)
.ToListAsync(ct);
}
// Program.cs: no proxies in the API context.
builder.Services.AddDbContext<ShopDbContext>(o => o
.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
// (Removed: .UseLazyLoadingProxies())
// Test helper: count SQL commands so a regression fails CI.
public sealed class CommandCounter : DbCommandInterceptor
{
private int _count;
public int Count => _count;
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
Interlocked.Increment(ref _count);
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
}
}
Select, so the API model is separate from the persistence model and can be versioned on its own.ReferenceHandler.IgnoreCycles and stopping there. Why it is wrong: the N+1 queries still run. Instead: treat it as a stopgap and project to DTOs.[JsonIgnore] on entity navigations. Why it is wrong: it couples the domain model to one serialiser and still hides the real problem. Instead: keep entities out of the API contract.WebApplicationFactory against real SQL Server (Testcontainers), realistic related data, and an assertion on the maximum command count per endpoint.This is less an EF Core bug than a contract design problem: the API exposed the persistence model. DTO projections fix performance, cycles and data leakage at once, and they make the API independent of entity changes. I also make the failure loud: lazy loading off for web contexts and a query-count assertion in integration tests.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| DTO projection | All API responses | DTO per endpoint | Never a bad default for reads |
Include + entity response |
Internal tools, quick prototypes | Over-fetching, contract coupling | Public or high-traffic APIs |
| Lazy loading | Desktop apps, long-lived contexts | Hidden N+1, AOT incompatible | Web APIs |
IgnoreCycles |
Emergency stopgap | Queries still run | As the permanent fix |
EF Core does not load navigation properties unless you ask. There are three ways:
Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.UseLazyLoadingProxies() and virtual navigations, the first access runs a query automatically.Filtered Include (EF Core 5+) lets you write Include(c => c.Orders.Where(o => o.IsOpen).OrderBy(o => o.PlacedAt).Take(5)).
The trade-off: eager is predictable, explicit is precise, lazy is convenient but hides N+1 queries.
For read-only endpoints I project with Select into a DTO. Include loads whole entities: every column of the root and of each included table, all materialised and (by default) tracked. A projection makes EF Core select only the columns the DTO references, turns o.Lines.Count() or Sum into SQL subqueries, and returns DTOs that are never tracked, so there's no snapshot cost.
Select are joined automatically; no Include is needed (and Include is ignored there).Include is still right when I load an aggregate to modify and save it, because I need tracked entities.The trade-off: projection means writing a DTO per use case, in exchange for less I/O, less memory and no tracking.
How to tell it (STAR)
**S:** At [company], our order history endpoint jumped from [120 ms] to [2.5 s] p95 right after a release, and some calls failed with a JSON cycle error. **T:** As [the on-call engineer] I had to stop the errors and find the cause. **A:** Application Insights showed about 150 SQL calls per request. I reproduced it with a command-counting interceptor and saw the serialiser walking lazy-loaded navigations, including a new back-reference from customer to orders. I shipped `IgnoreCycles` as a stopgap, then replaced entity responses with DTO projections and turned off lazy loading in the API. **R:** The endpoint went to [one query and ~80 ms], we stopped leaking [internal fields], and query-count tests have caught [two] similar regressions since.
Last updated 23 Nov 2026.