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.
A value converter tells EF Core how to turn a .NET value into a column value and back, configured with HasConversion.
HasConversion<string>() plus HasMaxLength(20). Readable in SQL and safe when enum members are reordered.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.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.
"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>()storesOrderStatus.Shippedas 'Shipped'. I always addHasMaxLength, otherwise it'snvarchar(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 aValueConverter<OrderId, Guid>, and register it for everyOrderIdproperty withConfigureConventions, 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 aValueComparerthat compares contents and takes a deep snapshot. Second, queries: EF Core translates comparisons on the converted value as a whole, soo.Id == orderIdworks, buto.Id.Value == guidfails 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."
| 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) |
| 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" |
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.
Checks practical mastery of value converters and their limits in a DDD-style model.
Green flags
ConfigureConventionso.Id.Value and string-sorting pitfallsRed flags
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.
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.
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.
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.
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.
OrderBy it; read the SQL and see the alphabetical order.Where(o => o.Id.Value == guid) and see the exception; fix it.List<string> with a converter but no comparer, add an item, and see that SaveChanges writes nothing.Contains.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
HasMaxLength. Why it is wrong: the column becomes nvarchar(max) and can't be indexed. Instead: HasConversion<string>().HasMaxLength(20).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).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.ValueComparer with a deep snapshot, or make the type immutable.ComplexProperty with Amount (HasPrecision(18, 2)) and Currency (HasMaxLength(3)) columns.HasConversion for every typed-ID property. Why it is wrong: one forgotten property breaks queries. Instead: ConfigureConventions with HaveConversion.ValueGeneratedNever().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.
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.
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.
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.
Last updated 23 Nov 2026.