📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do JSON columns work in EF Core 10? Explain mapping with ToJson on complex and owned types, how queries inside the JSON are translated, what the native SQL Server json type changes, how updates and indexing work, and when a JSON column is better than extra tables.

Covers EF Core JSON mapping: ToJson on owned types (EF Core 7+) and complex types (EF Core 10), primitive collections, translation to JSON_VALUE/OPENJSON, partial updates with JSON_MODIFY, the native json data type used with Azure SQL and SQL Server 2025 (compatibility level 170), indexing through computed columns, ExecuteUpdate on JSON properties, and the design trade-offs versus normalised tables.

Mid-Level Theory Intermediate complex-types data-modelling ef-core ef-core-10 json-columns sql-server

🎯 Key points

  • ToJson() maps an owned type (EF Core 7+) or a complex type (EF Core 10) and its nested collections into one column
  • Primitive collections (List<string>, int[]) map to a JSON array column by default since EF Core 8
  • Queries into JSON translate to JSON_VALUE / OPENJSON, so filtering, projecting and ordering stay in SQL
  • Changing one property sends JSON_MODIFY instead of rewriting the document
  • EF Core 10 uses the native json data type with UseAzureSql or compatibility level 170 (SQL Server 2025); nvarchar(max) otherwise
  • Indexing: a persisted computed column over JSON_VALUE plus a normal index; no foreign keys or constraints inside JSON
  • Good fit: aggregate-owned, read together, variable shape; poor fit: queried independently, referenced by other rows, or updated concurrently in parts
  • Complex types are value semantics, preferred over owned types for new JSON mapping in EF Core 10

⏱ 30-second answer

A JSON column stores a whole value object or collection (an address, a list of options, a settings bag) in one column. In EF Core you map it with ToJson(): on owned types since EF Core 7, and on complex types since EF Core 10, which is now the better default. Primitive collections such as List<string> map to a JSON array automatically. LINQ into the document translates to JSON_VALUE and OPENJSON, so it runs in SQL, and changing one property sends JSON_MODIFY rather than rewriting the document. With UseAzureSql or compatibility level 170 (SQL Server 2025), EF Core 10 uses the native json type instead of nvarchar(max). Index hot paths through persisted computed columns. The trade-off: fewer joins and a flexible shape versus no foreign keys, weaker indexing and awkward independent queries.

🗣 Full answer (senior)

How I would answer this in an interview

"A JSON column is a way to store data that belongs to one row and is read with it, without splitting it into child tables. In EF Core, I map a type with ToJson(). EF Core 7 introduced that for owned entity types; EF Core 10 added it for complex types, which have proper value semantics: no hidden key, compared by value, and assignable as a whole. For new code that's what I use. List<string> or int[] properties don't even need configuration: since EF Core 8 they map to a JSON array column.

The useful part is that the JSON isn't opaque to LINQ. Where(o => o.Shipping.Postcode == \"3000\") becomes JSON_VALUE([o].[Shipping], '$.Postcode') = N'3000', and querying inside a JSON collection uses OPENJSON as a table source. On save, if I change one property, EF sends JSON_MODIFY for that path instead of rewriting the document. On Azure SQL and SQL Server 2025, EF Core 10 uses the native json data type when I configure UseAzureSql or the compatibility level is 170. It's stored in an optimised binary format and validated on write, instead of being nvarchar(max) text.

The question I always ask is 'is this data owned by the row?'. Order shipping details, product attributes that vary by category, a user's notification preferences: yes, they're read and written with the parent. Order lines, which are reported on, joined to products and updated separately: no, they're rows. JSON gives up foreign keys, CHECK constraints on inner values and cheap indexing; for a hot filter I add a persisted computed column over JSON_VALUE and index that. The mistake I see is using JSON to avoid a migration. It moves the schema into the application, and the first reporting request then turns into OPENJSON gymnastics."


Mapping options

Mapping Since Shape in SQL Notes
Owned type + ToJson() EF Core 7 One JSON column Has a hidden key; reference semantics
Complex type + ToJson() EF Core 10 One JSON column Value semantics; recommended for new code
Primitive collection EF Core 8 JSON array column List<string>, int[], DateOnly[]
Value converter to string Any Opaque text No LINQ into it; avoid

JSON column vs child tables

Question JSON column Child table
Read and written with the parent? Yes Sometimes
Queried or reported on independently? Poorly Yes
Referenced by other rows (FKs)? No Yes
Shape varies per row? Fine Needs EAV or many nullable columns
Concurrent partial updates? Whole row conflicts Row-level

Production example

Moving variable product attributes from an EAV table ([~45M] rows) into a JSON column on Products removed a [6-way] join from the product page: p95 went from [210 ms] to [28 ms]. The two attributes used in filters got persisted computed columns with indexes.

🔍 What the interviewer is checking

Checks current EF Core JSON support and the judgement to know when JSON beats tables.

Green flags

  • Knows ToJson() on owned and complex types, and primitive collections.
  • Explains JSON_VALUE/OPENJSON translation and JSON_MODIFY updates.
  • Mentions the native json type in EF Core 10 with Azure SQL / SQL Server 2025.
  • Gives clear criteria and the indexing workaround.

Red flags

  • Stores JSON as a string with a converter.
  • Uses JSON to avoid modelling relationships.
  • Unaware that querying inside JSON can be translated.

📚 Learn in depth

1. What EF stores

public sealed record Address(string Street, string Suburb, string State, string Postcode);
public sealed class Order { public int Id { get; set; } public Address Shipping { get; set; } = default!; public List<string> Tags { get; set; } = []; }

modelBuilder.Entity<Order>().ComplexProperty(o => o.Shipping, c => c.ToJson());
Orders
Id | Shipping (json)                                                   | Tags (json)
1  | {"Street":"1 Main St","Suburb":"Carlton","State":"VIC","Postcode":"3053"} | ["gift","priority"]

2. Query translation

db.Orders.Where(o => o.Shipping.State == "VIC" && o.Tags.Contains("priority")).Select(o => new { o.Id, o.Shipping.Suburb });
SELECT [o].[Id], JSON_VALUE([o].[Shipping], '$.Suburb') AS [Suburb]
FROM [Orders] AS [o]
WHERE JSON_VALUE([o].[Shipping], '$.State') = N'VIC'
  AND N'priority' IN (SELECT [t].[value] FROM OPENJSON([o].[Tags]) AS [t])

EF Core also uses OPENJSON to pass collections as a single parameter (WHERE Id IN (SELECT value FROM OPENJSON(@ids))), which is unrelated to JSON columns but uses the same machinery.

3. Updates

order.Shipping = order.Shipping with { Postcode = "3054" };
-> UPDATE [Orders] SET [Shipping] = JSON_MODIFY([Shipping], 'strict $.Postcode', @p0) WHERE [Id] = @p1

EF Core 10 also supports ExecuteUpdateAsync setting properties inside JSON for set-based changes.

4. The native json type

SQL Server 2025 and Azure SQL have a json data type: stored in a binary format, validated on insert, faster to read with JSON_VALUE. EF Core 10 uses it by default for JSON columns and primitive collections when you configure UseAzureSql(...) or UseSqlServer(..., o => o.UseCompatibilityLevel(170)). Upgrading an existing model changes column types, so the next migration will contain ALTER COLUMN ... json. Review it like any other type change, or pin the old type with HasColumnType("nvarchar(max)") until you're ready.

5. Indexing

ALTER TABLE Orders ADD ShippingState AS JSON_VALUE(Shipping, '$.State') PERSISTED;
CREATE INDEX IX_Orders_ShippingState ON Orders (ShippingState);

The optimiser matches JSON_VALUE(Shipping, '$.State') in queries to the computed column. In EF Core, add a shadow property with HasComputedColumnSql(..., stored: true) and HasIndex. SQL Server 2025 also introduces a JSON index for the json type; check its status and limitations on your target before relying on it.

6. Limits

  • No foreign keys, unique constraints or CHECKs on inner values (beyond ISJSON / type validation).
  • Concurrency is per row: two users editing different inner properties conflict.
  • Large documents are rewritten in the log on many changes; keep documents small (KBs, not MBs).
  • Schema evolution: renaming a property leaves old documents with the old name; you need a data migration or tolerant deserialisation.

Try it yourself

  1. Map an Address complex type with ToJson(), filter on State and read ToQueryString().
  2. Change one property and capture the JSON_MODIFY in LogTo output.
  3. Switch to UseAzureSql and add a migration: inspect the column type change.
  4. Add a persisted computed column over JSON_VALUE and compare plans with and without its index on 1M rows.
  5. Rename a property in the C# type and observe what happens to existing documents.

💻 Code

Mapping a complex type and a primitive collection to JSON, plus an index for a hot filter.

namespace Shop.Data;

using Microsoft.EntityFrameworkCore;

public sealed record Address(string Street, string Suburb, string State, string Postcode);
public sealed record GiftOptions(bool Wrap, string? Message);

public sealed class Order
{
    public int Id { get; set; }
    public required Address Shipping { get; set; }
    public GiftOptions? Gift { get; set; }
    public List<string> Tags { get; set; } = [];          // primitive collection -> JSON array
}

public sealed class ShopDbContext(DbContextOptions<ShopDbContext> o) : DbContext(o)
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        var order = b.Entity<Order>();
        order.ComplexProperty(o => o.Shipping, c => c.ToJson());   // EF Core 10: complex type as JSON
        order.ComplexProperty(o => o.Gift, c => c.ToJson());

        // Hot filter: persisted computed column + index (no direct index on JSON paths).
        order.Property<string>("ShippingState")
             .HasComputedColumnSql("JSON_VALUE([Shipping], '$.State')", stored: true)
             .HasMaxLength(3);
        order.HasIndex("ShippingState");
    }
}
// Program.cs: UseAzureSql makes EF Core 10 use the native json type.
builder.Services.AddDbContext<ShopDbContext>(o =>
    o.UseAzureSql(builder.Configuration.GetConnectionString("Shop")));

// Query stays in SQL: JSON_VALUE / OPENJSON.
var vicPriority = await db.Orders
    .Where(o => o.Shipping.State == "VIC" && o.Tags.Contains("priority"))
    .Select(o => new { o.Id, o.Shipping.Suburb })
    .ToListAsync(ct);

⚠ Common mistakes

  • Mistake: Storing JSON through a value converter to string. Why it is wrong: EF can't translate LINQ into it, so filters run in memory or fail. Instead: ToJson() or primitive collections.
  • Mistake: Putting data that other rows reference, or that is reported on independently, into JSON. Why it is wrong: no foreign keys and every report needs OPENJSON. Instead: keep it in tables.
  • Mistake: Filtering on a JSON path in a hot query with no index support. Why it is wrong: JSON_VALUE over every row is a scan. Instead: a persisted computed column with an index.
  • Mistake: Upgrading to EF Core 10 with UseAzureSql and applying the next migration without reading it. Why it is wrong: it changes column types to json, a heavy operation on big tables. Instead: review it, schedule it, or pin nvarchar(max) for now.
  • Mistake: Renaming C# properties of a JSON-mapped type without a data migration. Why it is wrong: existing documents keep the old name and the values read back as null. Instead: use HasJsonPropertyName to keep the stored name, or migrate the data.
  • Mistake: Large, frequently edited documents. Why it is wrong: every edit rewrites a big value, increases log volume, and concurrency conflicts hit the whole row. Instead: keep documents small or split them out.
  • Mistake: Choosing owned types for new JSON mapping in EF Core 10. Why it is wrong: owned types carry hidden keys and reference semantics that complicate value objects. Instead: complex types with ToJson().

🏛 Senior insight: trade-offs

JSON columns are a modelling decision, not a shortcut. I use them where the data is genuinely part of the aggregate and its shape varies: attributes, preferences, snapshots of an address at order time. And I keep anything relational relational. The EF Core 10 combination of complex types, the native json type and ExecuteUpdate into JSON makes the happy path much better than in EF Core 7, but the database still can't enforce integrity inside the document, so validation moves into the application and tests.

I measure with actual plans (looking for JSON_VALUE scans) and log volume, and I plan schema evolution up front: HasJsonPropertyName for renames, and tolerant reads for documents written by older versions.

Option When it fits Cost When not to
JSON complex type Owned, variable-shape data read with the parent No FKs, weaker indexing Independent queries, references
Primitive collection Small lists of tags, ids Same Lists that need their own attributes
Child table Relational data, reporting Joins Truly owned, variable data
Table splitting / columns Fixed-shape value objects Wider table Variable shapes

🔗 Follow-ups the interviewer may ask

  1. When: Candidate discusses indexing JSON or choosing JSON over tables. Why: Checks the narrower decision and indexing question.
    How to answer

    Use a JSON column (ComplexProperty(...).ToJson() or OwnsOne/OwnsMany(...).ToJson()) for data that is owned by one row, read and written with it, and rarely queried alone: preferences, a variable set of attributes, a snapshot of an address at order time. Use tables when you need to join, filter or aggregate across rows at scale, enforce foreign keys, unique or check constraints, or update parts concurrently. Performance trade-off: reading the whole document with its owner is cheap (one row, no join), but filtering inside JSON means parsing every document unless you index it. On SQL Server, index a property by adding a computed column over JSON_VALUE(Data, '$.Country') and indexing that column; it works on every supported version. EF Core 10 can map to the native json data type on Azure SQL and SQL Server 2025, which stores documents in a binary form that is faster to read; check your target's support for dedicated JSON indexes before relying on them.

  2. When: Candidate mentions complex types or owned types. Why: Checks the wider choice between owned entities, complex types and JSON.
    How to answer

    Both map value objects (no identity, compared by value) into the owner's table or a JSON column.

    • Owned entities (OwnsOne, OwnsMany) are really entities with a hidden key. They have reference semantics: you can't assign the same Address instance to two owners, and OwnsMany defaults to a separate table.
    • Complex types (ComplexProperty, EF Core 8+) have value semantics: no key, can be records or structs, and assigning one copies the values. EF Core 10 added optional complex types, complex collections and JSON mapping with ToJson().

    Today I default to complex types for value objects, which is also what the EF Core 10 release notes recommend, and keep owned types for models that already use them or need rows in a separate table. The trade-off: columns (table splitting) are indexable and typed; JSON is flexible but harder to index and constrain.

🛠 Real-world problems: how you handle them

Product filter on a JSON attribute scanning 3M rows
Situation
An online [hardware] store on Azure SQL moved category-specific product attributes into a JSON column. Category pages filter by [voltage] and [brand] inside the JSON. [~3M] products.
Signals
Category page p95 rose from [90 ms] to [1.4 s] after the release; Azure SQL DTU at [85%]; Query Store showed one query with high CPU and a clustered index scan.
Investigation
Read the generated SQL with `ToQueryString()`: `WHERE JSON_VALUE([p].[Attributes], '$.Voltage') = @v`. The actual execution plan showed a full scan evaluating `JSON_VALUE` per row. Checked which JSON paths were used in filters: [two] accounted for [95%] of queries.
Resolution
Immediately: added persisted computed columns over the two paths with nonclustered indexes in a hot-fix migration (online index build). Then: mapped them as shadow properties in EF, added an analysis step to the design checklist for any new filtered JSON path, and evaluated the native `json` type on the target compatibility level.
Prevention
Query Store regression alerts; a performance test of category pages at production-sized data; design review rule: any JSON path used in a filter needs an index plan; plan check in the PR for new JSON queries.

How to tell it (STAR)

**S:** At [company], we moved product attributes into a JSON column and category pages slowed from [90 ms] to [1.4 seconds]. **T:** I owned the fix. **A:** Query Store pointed to one query, and its plan showed a full scan evaluating `JSON_VALUE` on every one of [3M] rows. Two attribute paths covered almost every filter, so I added persisted computed columns over them with indexes, mapped them in EF Core, and added a rule that any filtered JSON path needs an index plan before it ships. **R:** p95 went back to [~70 ms], database CPU dropped by [half], and we kept the flexibility of JSON for the long tail of attributes.

↩ Usually asked after

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me