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

📚 Interview question

Show how you use value converters in EF Core: store an enum as a string, map strongly typed IDs such as OrderId, and handle a Money value object. When do you need a value comparer, and which LINQ queries break on converted properties?

Covers EF Core value converters (HasConversion, built-in and custom ValueConverter), enums as strings, strongly typed IDs with record structs and ConfigureConventions, value comparers for mutable types, why Money fits a complex type better, and query translation pitfalls.

Mid-Level Coding Intermediate ddd ef-core strongly-typed-ids value-comparer value-converters value-objects

🎯 Key points

  • HasConversion<string>() for enums; set HasMaxLength so it isn't nvarchar(max)
  • Strongly typed ID: readonly record struct OrderId(Guid Value) + ValueConverter
  • ConfigureConventions: Properties<OrderId>().HaveConversion<OrderIdConverter>() for every use
  • A converter maps one property to one column; Money (amount + currency) is a ComplexProperty with two configured columns
  • EF Core 8+ maps List<string>/int[] as primitive collections (JSON) with no converter
  • Value comparer needed when you do convert a mutable reference type, or edits go undetected
  • Query on the converted type (o.Id == id), not o.Id.Value: member access on converted values doesn't translate
  • Converted strings compare as strings in SQL: ORDER BY / < on enum-as-string sorts alphabetically

⏱ 30-second answer

A value converter tells EF Core how to turn a .NET value into a column value and back, configured with HasConversion.

  • Enums as strings: HasConversion<string>() plus HasMaxLength(20). Readable in SQL and safe when enum members are reordered.
  • Strongly typed IDs: readonly record struct OrderId(Guid Value) with a ValueConverter<OrderId, Guid>, applied model-wide in ConfigureConventions. The compiler stops you passing a CustomerId where an OrderId belongs.
  • Money has two parts (amount, currency), so it is a complex type, not a converter: converters map one property to one column.

You need a value comparer when the converted type is mutable (say List<string> stored as JSON), or edits go unnoticed. In LINQ, compare the whole converted value (o.Id == id); o.Id.Value usually doesn't translate. The trade-off: richer domain types versus a few query restrictions.

🗣 Full answer (senior)

How I would answer this in an interview

"A value converter is a pair of expressions, model-to-provider and provider-to-model, that EF Core applies when it reads and writes a property and when it parameterises queries. The everyday one is enums: HasConversion<string>() stores OrderStatus.Shipped as 'Shipped'. I always add HasMaxLength, otherwise it's nvarchar(max). Strings survive someone reordering the enum, which integer storage doesn't, and they make the data readable for reporting.

The more interesting use is strongly typed IDs. I define readonly record struct OrderId(Guid Value), write a ValueConverter<OrderId, Guid>, and register it for every OrderId property with ConfigureConventions, so I don't repeat it per entity. Now a method that takes (OrderId, CustomerId) can't be called with the arguments swapped, which is a real bug class. For Money I don't use a converter, because a converter maps one property to one column and Money needs amount and currency. That's a complex type: two columns, value semantics.

Two pitfalls. First, value comparers: EF Core detects changes by comparing snapshots, and for a mutable reference type like a List<string> stored as JSON, the default comparison is by reference, so adding an item isn't detected unless I supply a ValueComparer that compares contents and takes a deep snapshot. Second, queries: EF Core translates comparisons on the converted value as a whole, so o.Id == orderId works, but o.Id.Value == guid fails or falls back to an exception, and string functions or < on an enum stored as a string compare strings, so 'Cancelled' sorts before 'Pending'. The mistake I see is adding converters everywhere and then writing LINQ that can't translate."


What to use for which value

Value Mapping Columns
Enum HasConversion<string>() 1 (nvarchar(20))
Strongly typed ID ValueConverter<OrderId, Guid> 1
Email (validated string) Converter to string 1
Money (amount + currency) ComplexProperty 2
List<string> tags Primitive collection (EF Core 8+) or converter + comparer 1 (JSON)

Built-in conversions

Call Stores as
HasConversion<string>() on enum Name
HasConversion<int>() on enum Number (default)
HasConversion<long>() on DateTimeOffset Ticks-based long
HasConversion<string>() on bool "True"/"False"

Production example

Introducing strongly typed IDs across [40] entities at [company] surfaced [6] call sites that passed a customer id where an account id was expected; two had already caused misrouted notifications. Query performance was unchanged because the converter compiles to a simple member access in the materialiser and the SQL is identical.

🔍 What the interviewer is checking

Checks practical mastery of value converters and their limits in a DDD-style model.

Green flags

  • Applies typed-ID converters with ConfigureConventions
  • Knows when a value comparer is required
  • Knows Money belongs in a complex type
  • Spots o.Id.Value and string-sorting pitfalls

Red flags

  • Serialises multi-part values into strings
  • Unaware that converted properties change how LINQ translates

📚 Learn in depth

1. Where converters run

write:  OrderId ──ConvertToProvider──► Guid ──► SqlParameter (uniqueidentifier)
read:   uniqueidentifier ──► Guid ──ConvertFromProvider──► OrderId
query:  o.Id == orderId  →  [o].[Id] = @orderId   (parameter converted with the same converter)

Converters are expression trees, so EF Core compiles them into the materialiser; there is no reflection per row.

2. Why member access on converted values fails

The SQL column holds a Guid, not an OrderId. o.Id.Value asks EF Core to translate a member of a type the database doesn't know. EF Core can only treat the converted property as an opaque value of the provider type. Compare whole values, or map the raw column as well.

3. Value comparers and snapshots

Change tracking stores a snapshot per property and compares it with the current value on DetectChanges. The ValueComparer defines three expressions: equality, hash code, and snapshot (how to copy the value). For immutable types (record structs, strings) the default is fine. For a mutable List<string>, the snapshot must be a copy, or both sides point at the same list and always compare equal.

4. Key converters

When a key uses a converter, EF Core can't use its normal value generation for the provider type automatically in every case. For typed GUID ids, create the id in the domain (OrderId.New()) and mark the key ValueGeneratedNever(), or register a custom ValueGenerator.

5. Primitive collections

Since EF Core 8, List<string> or int[] properties map to a JSON column automatically and are queryable (OPENJSON), so a hand-written converter is rarely needed for simple lists.

Try it yourself

  1. Store an enum as a string and OrderBy it; read the SQL and see the alphabetical order.
  2. Write Where(o => o.Id.Value == guid) and see the exception; fix it.
  3. Map List<string> with a converter but no comparer, add an item, and see that SaveChanges writes nothing.
  4. Replace the converter with an EF Core 8+ primitive collection and query it with Contains.

💻 Code

Enum as string, strongly typed IDs applied model-wide, and a mutable value with a comparer.

namespace Shop.Domain;

public readonly record struct OrderId(Guid Value)
{
    public static OrderId New() => new(Guid.CreateVersion7()); // created in the domain, before save
}

public enum OrderStatus { Pending, Paid, Shipped, Cancelled }

public sealed class Order
{
    public OrderId Id { get; private set; } = OrderId.New();
    public OrderStatus Status { get; set; }
    public List<string> Labels { get; set; } = [];   // mutable: needs a comparer if converted
}
namespace Shop.Infrastructure;

using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Shop.Domain;

public sealed class OrderIdConverter() : ValueConverter<OrderId, Guid>(id => id.Value, g => new OrderId(g));

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

    protected override void ConfigureConventions(ModelConfigurationBuilder b) =>
        b.Properties<OrderId>().HaveConversion<OrderIdConverter>();   // every OrderId, everywhere

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Order>(e =>
        {
            e.Property(o => o.Id).ValueGeneratedNever();             // the domain creates ids
            e.Property(o => o.Status).HasConversion<string>().HasMaxLength(20);

            // Shown for the comparer; on EF Core 8+ a primitive collection mapping does this for you
            e.Property(o => o.Labels).HasConversion(
                v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default),
                v => JsonSerializer.Deserialize<List<string>>(v, JsonSerializerOptions.Default) ?? new List<string>(),
                new ValueComparer<List<string>>(
                    (a, c) => a!.SequenceEqual(c!),
                    v => v.Aggregate(0, (h, s) => HashCode.Combine(h, s.GetHashCode())),
                    v => v.ToList()));                               // snapshot = a copy
        });
    }
}

// Correct:   db.Orders.Where(o => o.Id == orderId)
// Fails:     db.Orders.Where(o => o.Id.Value == guid)
SELECT [o].[Id], [o].[Labels], [o].[Status]
FROM [Orders] AS [o]
WHERE [o].[Id] = @orderId          -- parameter converted to uniqueidentifier

-- OrderBy(o => o.Status) with string storage sorts by name, not by enum value:
ORDER BY [o].[Status]              -- Cancelled, Paid, Pending, Shipped

⚠ Common mistakes

  • Mistake: Storing enums as strings without HasMaxLength. Why it is wrong: the column becomes nvarchar(max) and can't be indexed. Instead: HasConversion<string>().HasMaxLength(20).
  • Mistake: Writing o.Id.Value == guid in LINQ. Why it is wrong: members of converted types don't translate. Instead: compare whole values: o.Id == new OrderId(guid).
  • Mistake: Hand-writing a JSON converter for List<string> on EF Core 8+. Why it is wrong: EF Core 8+ already maps primitive collections (List<string>, int[]) to a JSON column automatically, with a correct comparer and translatable Contains/Any via OPENJSON; a custom converter makes the column opaque to queries. Instead: rely on primitive collection mapping; keep custom converters for types EF Core can't map.
  • Mistake: Converting a mutable type (a custom collection or class) without a value comparer. Why it is wrong: in-place edits aren't detected and aren't saved. Instead: supply a ValueComparer with a deep snapshot, or make the type immutable.
  • Mistake: Using a converter for a multi-part value like Money. Why it is wrong: you end up serialising two values into one string column that can't be summed in SQL. Instead: ComplexProperty with Amount (HasPrecision(18, 2)) and Currency (HasMaxLength(3)) columns.
  • Mistake: Sorting or range-filtering an enum stored as a string. Why it is wrong: SQL compares text alphabetically. Instead: store as int when ordering matters, or sort by an explicit order column.
  • Mistake: Repeating HasConversion for every typed-ID property. Why it is wrong: one forgotten property breaks queries. Instead: ConfigureConventions with HaveConversion.
  • Mistake: Expecting database-generated values for converted keys. Why it is wrong: generation may not apply to the custom type. Instead: generate ids in the domain and use ValueGeneratedNever().

🏛 Senior insight: trade-offs

Converters let the domain speak its own types while the database stays boring. The senior judgement is knowing their boundary: one property ↔ one column, translated as an opaque value. Anything with several parts or that you need to query inside belongs to complex types, primitive collections or JSON mapping.

Performance, precisely: a simple converter (typed ID, enum) is compiled into the materialiser and parameter setup, so the per-row cost is a delegate call measured in nanoseconds and the SQL is unchanged. Costs appear in three places. Serialising converters (JSON, XML) run a serializer per row on read and per changed row on DetectChanges, and their comparers snapshot by deep copy, so tracking 50,000 entities with a converted collection can add tens of milliseconds and noticeable allocations. Index use: a converter that changes the representation (e.g. DateTimeOffset to long, or case-normalising strings) means the SQL compares the stored form, and functions applied around it are non-sargable. Translation failures: queries that touch members of converted values throw at run time, and the usual "fix" of calling AsEnumerable() early pulls whole tables into memory, which is far more expensive than the converter ever was.

Option When it fits Cost When not to
Value converter Enums, typed IDs, single-value objects (Email) Query restrictions on members Multi-column values
Complex type Money, Address, DateRange More columns Values needing identity
Primitive collection Tags, small id lists JSON column, OPENJSON queries Large or relational data
Plain primitives Hot paths, reporting tables Primitive obsession Domain logic with mixed-up ids

Measure with BenchmarkDotNet (materialising 10k rows with and without the converter) and cover typed-ID queries with integration tests against SQL Server.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate converts a collection or mutable class. Why: Checks understanding of snapshot change tracking.
    How to answer

    EF Core detects changes by comparing each property's current value with the original value snapshot taken at load time. For immutable types (string, int, records you never mutate) copying the reference is a perfect snapshot. For a mutable type mapped through a value converter, such as a List<string> stored as JSON or a mutable class, the snapshot is the same object: change it in place (tags.Add("x")) and current and original are still equal, so the update is silently lost. A ValueComparer<T> tells EF Core three things: how to compare two values for equality, how to compute a hash code, and how to take a snapshot that is an independent copy (for a list, v => v.ToList()). EF Core 8+ supplies comparers for primitive collections automatically, but your own converters need one. A good comparer also avoids pointless UPDATEs, because equal values are no longer seen as modified.

  2. When: Candidate mentions value objects. Why: Checks the boundary between converters and complex types.
    How to answer

    A value converter maps one property to one column. Money has two parts, amount and currency, so a converter can only store it in one column: either a string like "12.50 AUD" or by dropping the currency. Either way SQL cannot filter, sort or SUM on the amount, cannot enforce the currency with a column constraint, and the LINQ query has to compare the whole converted value. A complex type (ComplexProperty(o => o.Total), EF Core 8+) maps Money to two typed columns in the owner's table (Total_Amount decimal(18,2), Total_Currency char(3)), so Where(o => o.Total.Amount > 100) and Sum translate to SQL. It has value semantics (no key, no identity, compared by value), works with immutable records, and lets Money keep its own behaviour, such as refusing to add AUD to NZD. Use a converter for single-value objects like OrderId or Email.

🛠 Real-world problems: how you handle them

Swapped customer and account ids misroute notifications
Situation
A billing platform at [company] with [40] entities used `Guid` for every id. Methods like `Notify(Guid customerId, Guid accountId)` were called from [dozens] of places.
Signals
Support tickets from customers receiving another account's payment reminders; logs showed notifications sent with valid ids for the wrong entity type.
Investigation
Traced one ticket through Application Insights to a handler that passed arguments in the wrong order; searched for similar call shapes and found more. EF Core logging confirmed queries used the swapped ids, returning real but wrong rows.
Resolution
Immediate: fixed the two faulty call sites and notified affected customers under the Privacy Act Notifiable Data Breaches assessment process. Real fix: introduced `readonly record struct` typed IDs with converters registered in `ConfigureConventions`; the compiler flagged [6] more swapped arguments.
Prevention
Typed IDs required for new entities (an analyser rule bans `Guid` parameters named `*Id` in application services); integration tests for typed-ID queries against SQL Server in Testcontainers.

How to tell it (STAR)

**S:** At [company] our billing platform used plain GUIDs for every id, and customers started getting reminders meant for other accounts. **T:** I had to stop the misrouting and make the bug class impossible. **A:** I traced it to swapped arguments, fixed the call sites, and then introduced strongly typed IDs as record structs with EF Core value converters registered once in `ConfigureConventions`. The SQL stayed identical, but the compiler found six more swapped calls. **R:** Misrouted notifications went to zero, no performance change, and typed IDs became the standard for every new entity.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me