Lesson 03 of 4 · 11 min read · Updated

EF Core 11: Indexing and Querying Nested Complex Types

A parcel on its way from Lisbon to Basel passes a pickup point, two or three sorting hubs and maybe a customs office. Each stop has a hub code, a kind and an address. None of these stops has an identity of its own: nobody looks up "stop number 3" by key, it only means something inside its shipment. A separate Stops table with a foreign key would work, but every query would pay for a join. EF Core's complex types model this kind of data as value objects without keys, stored inside the owning row, either as columns or as a JSON column.

EF Core 11 adds the feature that makes complex types useful for real lookups: indexes on properties of nested complex types. In this lesson we build a small shipment tracking store on PostgreSQL, index two levels deep with one line of HasIndex, read the real query plans, and find out what happens when the data we filter on sits inside a JSON collection.

The topic was inspired by Sarah Dutkiewicz's article EF Core 11: Querying Deeply Nested Game State Without Schema Friction. The scenario, the code and the measurements in this lesson are our own, made on EF Core 11 RC2.

Technical Requirements

  1. .NET 11 SDK (RC2 or later). Tested with 11.0.100-rc.2.26504.105, EF Core 11.0.0-rc.2.26504.105 and Npgsql EF provider 11.0.0-rc.2.
  2. Docker for PostgreSQL 17.
  3. The full source code is on GitHub: Fcakiroglu16/dotnetacademy, branch efcore11-nested-complex-indexes
git clone https://github.com/Fcakiroglu16/dotnetacademy.git
cd dotnetacademy
git switch efcore11-nested-complex-indexes
docker compose up -d --wait
dotnet tool restore
dotnet run --project src/ShipmentTracking.ConsoleApp -- all

Complex Types in Three Releases

  1. EF Core 8 introduced complex types: no key, mapped into the owner's table as columns. No collections, no optional complex types.
  2. EF Core 10 added optional complex types, ToJson() for complex types, and complex collections stored as JSON.
  3. EF Core 11 lets HasIndex follow a path through nested complex properties, for example s.Tracking.LastScan.HubCode.

The Model

src/ShipmentTracking.Data/Model/Shipment.cs

public sealed class Shipment
{
public Guid Id { get; init; }

public required string TrackingNumber { get; init; }

public DateTimeOffset CreatedAt { get; init; }

// Plan -> Stops -> Address: one jsonb column.
public required RoutePlan Plan { get; init; }

// Tracking -> Carrier / LastScan: ordinary columns (table splitting).
public required TrackingInfo Tracking { get; init; }
}

RoutePlan holds List<RouteStop> Stops. A RouteStop has a HubCode such as DE-HAM-2, a Kind (Pickup, Hub, Customs, Delivery) and an Address with CountryCode and City. TrackingInfo holds a Status, a CarrierInfo (Code, ServiceLevel) and a ScanInfo (HubCode, ScannedAt) for the last barcode scan. All of them are records with init properties.

Mapping: Columns for Tracking, JSON for the Route

src/ShipmentTracking.Data/ShippingDbContext.cs

protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Shipment>(shipment =>
{
shipment.HasKey(s => s.Id);
shipment.HasIndex(s => s.TrackingNumber).IsUnique();

// Stops is a collection, so the whole plan has to be JSON.
shipment.ComplexProperty(s => s.Plan, plan =>
{
plan.ToJson();
plan.ComplexCollection(p => p.Stops, stop =>
{
stop.ComplexProperty(st => st.Address);
stop.Property(st => st.Kind).HasConversion<string>();
});
});

// No collections below Tracking: every leaf becomes a column.
shipment.ComplexProperty(s => s.Tracking, tracking =>
{
tracking.Property(t => t.Status).HasConversion<string>();
tracking.ComplexProperty(t => t.Carrier);
tracking.ComplexProperty(t => t.LastScan);
});

// EF Core 11: index paths that go through nested complex types.
shipment.HasIndex(s => s.Tracking.LastScan.HubCode);
shipment.HasIndex(s => new { s.Tracking.Carrier.Code, s.Tracking.LastScan.ScannedAt });

Two shapes, two mappings. Stops is a list, and a complex collection must be mapped to JSON. Once the collection is JSON, its root must be JSON too, so the whole route plan becomes one jsonb column called Plan. Tracking contains no collections, so every leaf becomes an ordinary column in the same table: Tracking_Status, Tracking_Carrier_Code, Tracking_LastScan_HubCode, Tracking_LastScan_ScannedAt and so on. This split decides what can be indexed well.

Nested Indexes on Columns

The two HasIndex calls go two levels deep with plain lambdas. The generated migration contains ordinary index operations on the flattened columns:

migrationBuilder.CreateIndex(
name: "IX_Shipments_Tracking_LastScan_HubCode",
table: "Shipments",
column: "Tracking_LastScan_HubCode");

migrationBuilder.CreateIndex(
name: "IX_Shipments_Tracking_Carrier_Code_Tracking_LastScan_ScannedAt",
table: "Shipments",
columns: new[] { "Tracking_Carrier_Code", "Tracking_LastScan_ScannedAt" });

Two operational questions use them. *What is at hub DE-HAM-2 right now?* and *Which DHLX parcels have not been scanned for 25 days, oldest first?*

src/ShipmentTracking.Data/ShipmentQueries.cs

// Uses the index on Tracking_LastScan_HubCode.
public IQueryable<Shipment> AtHub(string hubCode) =>
db.Shipments.AsNoTracking()
.Where(s => s.Tracking.LastScan.HubCode == hubCode
&& s.Tracking.Status == ShipmentStatus.InTransit);

// Equality on the first column, range and sort on the second one.
public IQueryable<Shipment> NotScannedSince(string carrierCode, DateTimeOffset cutoff) =>
db.Shipments.AsNoTracking()
.Where(s => s.Tracking.Carrier.Code == carrierCode
&& s.Tracking.LastScan.ScannedAt < cutoff)
.OrderBy(s => s.Tracking.LastScan.ScannedAt);

The queries return IQueryable<Shipment>, so the console app prints the SQL with ToQueryString() and runs EXPLAIN ANALYZE on the exact command EF Core sends (CreateDbCommand() plus a prefix). The seeder creates 20,000 shipments with 3 to 7 stops across 20 countries and runs ANALYZE.

WHERE s."Tracking_Carrier_Code" = @carrierCode AND s."Tracking_LastScan_ScannedAt" < @cutoff
ORDER BY s."Tracking_LastScan_ScannedAt"
LIMIT @p

Limit (actual rows=20 loops=1)
-> Index Scan using "IX_Shipments_Tracking_Carrier_Code_Tracking_LastScan_ScannedAt" on "Shipments" s
Index Cond: (("Tracking_Carrier_Code" = 'DHLX'::text) AND ("Tracking_LastScan_ScannedAt" < '2026-10-04 12:00:00+00'::timestamp with time zone))
Execution Time: 0.027 ms

The composite index handles the equality on the carrier, the range on the scan time and the sort in one scan, and PostgreSQL stops after 20 rows. The hub query uses a Bitmap Index Scan on IX_Shipments_Tracking_LastScan_HubCode and finishes in 0.1 ms. For column-mapped complex types, EF Core 11 indexing simply works.

Indexing a Fixed Position Inside the JSON

The first stop is always the pickup, so Stops[0].Address.CountryCode is the origin country. EF Core 11 accepts this in the model:

shipment.HasIndex(s => s.Plan.Stops[0].Address.CountryCode);

dotnet ef dbcontext script shows a correct expression index for it:

CREATE INDEX "IX_Shipments_Plan_Stops_Address_CountryCode"
ON "Shipments" (("Plan" #>> '{Stops,0,Address,CountryCode}'));

On RC2 there are two problems. First, dotnet ef migrations add fails while writing the model snapshot:

Cannot scaffold C# literals of type 'Microsoft.EntityFrameworkCore.Metadata.RelationalJsonIndex'.
The provider should implement CoreTypeMapping.GenerateCodeLiteral to support using it at design time.

Second, and more important, the LINQ query for the same path does not use that expression at all:

src/ShipmentTracking.Data/ShipmentQueries.cs

// Stops[0] translates to jsonb_to_recordset ... LIMIT 1: no index fits.
public IQueryable<Shipment> ShippedFrom(string countryCode) =>
db.Shipments.AsNoTracking()
.Where(s => s.Plan.Stops[0].Address.CountryCode == countryCode);
WHERE (
SELECT s0."Address" ->> 'CountryCode'
FROM ROWS FROM (jsonb_to_recordset(s."Plan" -> 'Stops') AS ("Address" jsonb)) WITH ORDINALITY AS s0
LIMIT 1 OFFSET 0) = @countryCode

Seq Scan on "Shipments" s (actual rows=983 loops=1)
Rows Removed by Filter: 19017
Execution Time: 13.455 ms

The index expression is #>>, the query is a sub-select over jsonb_to_recordset. PostgreSQL can only use an expression index when the query contains the same expression, so even a hand-created index stays unused. We tested it: with the index in place, the raw #>> filter took 0.9 ms, while the EF Core query stayed a sequential scan.

The Fix: A Stored Generated Column

Let PostgreSQL copy the value out of the JSON into a real column, and index that column. It is a shadow property, so the domain model stays clean:

src/ShipmentTracking.Data/ShippingDbContext.cs

// The origin country, copied out of the JSON by PostgreSQL itself.
shipment.Property<string>(OriginCountry)
.HasComputedColumnSql("""("Plan" #>> '{Stops,0,Address,CountryCode}')""", stored: true);
shipment.HasIndex(OriginCountry);

This one goes through migrations without problems (computedColumnSql: "(\"Plan\" #>> '{Stops,0,Address,CountryCode}')", stored: true). The query reads the shadow property with EF.Property:

src/ShipmentTracking.Data/ShipmentQueries.cs

// The stored generated column has an ordinary B-tree index.
public IQueryable<Shipment> ShippedFromColumn(string countryCode) =>
db.Shipments.AsNoTracking()
.Where(s => EF.Property<string>(s, ShippingDbContext.OriginCountry) == countryCode);
Bitmap Heap Scan on "Shipments" s (actual rows=983 loops=1)
-> Bitmap Index Scan on "IX_Shipments_OriginCountry" (actual rows=983 loops=1)
Execution Time: 0.373 ms

Both versions returned the same 983 shipments. PostgreSQL updates a stored generated column on every insert and update, so it can never drift from the JSON.

Searching Every Stop: LINQ and a GIN Index

A generated column only works for a fixed position. *Which shipments cleared customs in Basel?* has to look at every stop. EF Core 11 translates Any() over the JSON collection, nested Address included:

src/ShipmentTracking.Data/ShipmentQueries.cs

// LINQ over the JSON collection: correct, but no index can serve it.
public IQueryable<Shipment> ClearedCustomsIn(string city) =>
db.Shipments.AsNoTracking()
.Where(s => s.Plan.Stops.Any(st => st.Kind == StopKind.Customs && st.Address.City == city));
WHERE EXISTS (
SELECT 1
FROM ROWS FROM (jsonb_to_recordset(s."Plan" -> 'Stops') AS ("Kind" text, "Address" jsonb)) WITH ORDINALITY AS s0
WHERE s0."Kind" = 'Customs' AND (s0."Address" ->> 'City') = @city)

Seq Scan on "Shipments" s (actual rows=311 loops=1)
Rows Removed by Filter: 19689
Execution Time: 17.305 ms

Correct, but every row's JSON is unpacked. PostgreSQL can index a whole jsonb value for containment (@>) with a GIN index. The EF model cannot express a GIN index with an operator class, so it goes into a hand-written migration (created with dotnet ef migrations add AddPlanGinIndex and edited):

src/ShipmentTracking.Data/Migrations/20261028214301_AddPlanGinIndex.cs

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("""CREATE INDEX "IX_Shipments_Plan_Gin" ON "Shipments" USING GIN ("Plan" jsonb_path_ops);""");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("""DROP INDEX "IX_Shipments_Plan_Gin";""");
}

On RC2 EF.Functions.JsonContains translates for a complex JSON property, so the containment query stays in LINQ. The pattern is one JSON document that describes "a stop of kind Customs whose address city is Basel":

src/ShipmentTracking.Data/ShipmentQueries.cs

// One @> containment check: the GIN index on Plan can serve it.
public IQueryable<Shipment> ClearedCustomsInContainment(string city)
{
// {"Stops":[{"Kind":"Customs","Address":{"City":"Basel"}}]}
var pattern = JsonSerializer.Serialize(new
{
Stops = new[] { new { Kind = nameof(StopKind.Customs), Address = new { City = city } } }
});

return db.Shipments.AsNoTracking()
.Where(s => EF.Functions.JsonContains(s.Plan, pattern));
}
WHERE s."Plan" @> @pattern

Bitmap Heap Scan on "Shipments" s (actual rows=311 loops=1)
Rows Removed by Index Recheck: 982
-> Bitmap Index Scan on "IX_Shipments_Plan_Gin" (actual rows=1293 loops=1)
Execution Time: 1.901 ms

jsonb_path_ops hashes each path and value separately, so the index also finds shipments where "Customs" and "Basel" appear in *different* stops. That is why 982 rows are removed by the recheck. The result is still exact: 311 shipments, the same as the LINQ version.

Results

20,000 shipments. Server time from EXPLAIN ANALYZE, .NET time is the median of 9 runs including reading the rows (bench command).

QuestionQueryPlanServer.NET median
In transit at a hubAtHubBitmap Index Scan, nested index0.10 ms0.8 ms
Not scanned for 25 daysNotScannedSinceIndex Scan, composite nested index0.03 ms0.6 ms
Origin countryShippedFrom (Stops[0])Seq Scan + jsonb_to_recordset13.5 ms13.2 ms
Origin countryShippedFromColumnBitmap Index Scan, generated column0.37 ms9.4 ms
Customs in BaselClearedCustomsIn (Any)Seq Scan + jsonb_to_recordset17.3 ms16.8 ms
Customs in BaselClearedCustomsInContainmentBitmap Index Scan, GIN1.9 ms4.7 ms

The .NET time for the origin query is dominated by reading 983 rows with their JSON, not by finding them. The GIN index is not always chosen: for "delivered to Portugal" (999 rows, 5% of the table) the planner preferred a sequential scan, which still took 6.4 ms instead of 18.4 ms because @> is cheaper than unpacking the JSON.

Gotchas

JSON shape changes produce no migration. We added int? DwellMinutes to RouteStop (inside Plan) and int Priority to CarrierInfo (a column):

ChangeMigration EF Core generatesExisting rows
CarrierInfo.Priority (column)AddColumn<int>("Tracking_Carrier_Priority", nullable: false, defaultValue: 0)Get 0
RouteStop.DwellMinutes (inside JSON)An empty Up() methodRead null

Use nullable types for new JSON properties, so "not recorded yet" and "zero" stay different.

**FromSql on an entity with a JSON complex collection fails.** db.Shipments.FromSql(...) threw a NullReferenceException on RC2. Database.SqlQuery<Guid> works, and JsonContains removes most reasons for raw SQL here.

The generated column is read in every query. OriginCountry appears in each SELECT of a Shipment. It is a short text column, so the cost is small. EF Core never writes it.

Don't migrate at startup in production. The console app calls Database.MigrateAsync() as a demo shortcut. Use migration bundles or scripts instead.

A Minimal API on Top

The sample also has a Minimal API on port 5081 that reuses ShipmentQueries. Its projection is an Expression<Func<Shipment, ShipmentDto>>, so EF Core reads only the needed columns:

GET /shipments/stale/DHLX?days=25 -> [{"trackingNumber":"TRK0006077","carrier":"DHLX","lastHub":"BG-SOF-1","lastScan":"2026-09-29T17:03:00+00:00","origin":"IT","stops":6}, ...]
GET /shipments/from/PT/count -> 983
GET /shipments/customs/Basel/count -> 311

Summary

  1. EF Core 11 indexes nested complex properties with plain lambdas, for example HasIndex(s => new { s.Tracking.Carrier.Code, s.Tracking.LastScan.ScannedAt }). When the nested type is mapped to columns, the migration is ordinary and PostgreSQL uses the index.
  2. Complex collections must be JSON, and so must their root. Keep the values you filter on often outside the collection.
  3. An index on a fixed JSON position (Stops[0]) is accepted by the model, but on RC2 migrations add cannot scaffold it, and the LINQ query does not match its expression. A stored generated column with a normal index works today.
  4. Any() over a JSON collection translates to jsonb_to_recordset and a sequential scan. A hand-written GIN migration plus EF.Functions.JsonContains gives an index-backed alternative for selective questions.
  5. Adding properties inside a JSON column needs no migration. Make them nullable.