Lesson 03 of 4 · 11 min read · Updated
EF Core 11: Indexing and Querying Nested Complex Types
On this page
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
- .NET 11 SDK (RC2 or later). Tested with
11.0.100-rc.2.26504.105, EF Core11.0.0-rc.2.26504.105and Npgsql EF provider11.0.0-rc.2. - Docker for PostgreSQL 17.
- The full source code is on GitHub: Fcakiroglu16/dotnetacademy, branch efcore11-nested-complex-indexes
Complex Types in Three Releases
- EF Core 8 introduced complex types: no key, mapped into the owner's table as columns. No collections, no optional complex types.
- EF Core 10 added optional complex types,
ToJson()for complex types, and complex collections stored as JSON. - EF Core 11 lets
HasIndexfollow a path through nested complex properties, for examples.Tracking.LastScan.HubCode.
The Model
src/ShipmentTracking.Data/Model/Shipment.cs
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
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:
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
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.
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:
dotnet ef dbcontext script shows a correct expression index for it:
On RC2 there are two problems. First, dotnet ef migrations add fails while writing the model snapshot:
Second, and more important, the LINQ query for the same path does not use that expression at all:
src/ShipmentTracking.Data/ShipmentQueries.cs
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
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
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
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
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
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).
| Question | Query | Plan | Server | .NET median |
|---|---|---|---|---|
| In transit at a hub | AtHub | Bitmap Index Scan, nested index | 0.10 ms | 0.8 ms |
| Not scanned for 25 days | NotScannedSince | Index Scan, composite nested index | 0.03 ms | 0.6 ms |
| Origin country | ShippedFrom (Stops[0]) | Seq Scan + jsonb_to_recordset | 13.5 ms | 13.2 ms |
| Origin country | ShippedFromColumn | Bitmap Index Scan, generated column | 0.37 ms | 9.4 ms |
| Customs in Basel | ClearedCustomsIn (Any) | Seq Scan + jsonb_to_recordset | 17.3 ms | 16.8 ms |
| Customs in Basel | ClearedCustomsInContainment | Bitmap Index Scan, GIN | 1.9 ms | 4.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):
| Change | Migration EF Core generates | Existing rows |
|---|---|---|
CarrierInfo.Priority (column) | AddColumn<int>("Tracking_Carrier_Priority", nullable: false, defaultValue: 0) | Get 0 |
RouteStop.DwellMinutes (inside JSON) | An empty Up() method | Read 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:
Summary
- 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. - Complex collections must be JSON, and so must their root. Keep the values you filter on often outside the collection.
- An index on a fixed JSON position (
Stops[0]) is accepted by the model, but on RC2migrations addcannot scaffold it, and the LINQ query does not match its expression. A stored generated column with a normal index works today. Any()over a JSON collection translates tojsonb_to_recordsetand a sequential scan. A hand-written GIN migration plusEF.Functions.JsonContainsgives an index-backed alternative for selective questions.- Adding properties inside a JSON column needs no migration. Make them nullable.