skip to content

In EF Core 10, what do the three expressions passed to ValueComparer<T> do, and when must a HasConversion property supply one?

level: seniorimportance: nice to knowfreq 26%

answer

  1. snapshot, then compare at SaveChanges
  2. equals, hash code, snapshot
  3. reference types: the snapshot is the same instance
  4. CoreEventId.CollectionWithoutComparer
  5. HaveConversion<TConversion, TComparer>()

basics

~20 s

A ValueComparer<T> holds an equality expression, a hash-code expression and a snapshot expression. A HasConversion property needs one when its type is a mutable reference type, because EF Core otherwise snapshots the same instance and misses edits made in place.

solid answer

~40 s

Change tracking takes a snapshot of each property when an entity is loaded and compares it with the current value at `SaveChanges`. For a converted property EF Core uses the type's `Equals`, and for a reference type the snapshot is the very same instance. A mutable `Dimensions` class converted to one column therefore never looks changed after `product.Size.WidthCm = 140`. `new ValueComparer<Dimensions>(equals, hashCode, snapshot)` fixes it: the snapshot expression makes a deep copy and the equality expression compares contents. Pass it as the third argument of `HasConversion`, or use `HaveConversion<TConversion, TComparer>()` in `ConfigureConventions`. EF Core warns about collection types converted without a comparer (`CollectionWithoutComparer`), but not about a mutable class. Immutable types, structs, complex types and primitive collections need no custom comparer.

code

csharp · 24 lines
csharp
public class Dimensions   // mutable type you cannot change
{
    public int WidthCm { get; set; }
    public int DepthCm { get; set; }
    public int HeightCm { get; set; }

    public static Dimensions Parse(string s)
    {
        var p = s.Split('x');
        return new Dimensions { WidthCm = int.Parse(p[0]), DepthCm = int.Parse(p[1]), HeightCm = int.Parse(p[2]) };
    }
}

var comparer = new ValueComparer<Dimensions>(
    (a, b) => a!.WidthCm == b!.WidthCm && a.DepthCm == b.DepthCm && a.HeightCm == b.HeightCm,
    d => HashCode.Combine(d.WidthCm, d.DepthCm, d.HeightCm),
    d => new Dimensions { WidthCm = d.WidthCm, DepthCm = d.DepthCm, HeightCm = d.HeightCm });

modelBuilder.Entity<Product>()
    .Property(p => p.Size)
    .HasConversion(
        d => d.WidthCm + "x" + d.DepthCm + "x" + d.HeightCm,
        s => Dimensions.Parse(s),
        comparer);

go deeper

for a junior

Recall that EF Core compares a loaded snapshot with the current value at SaveChanges, and that a ValueComparer controls that comparison.

for a middle

Explain the three expressions, why the snapshot must be a deep copy, and why a reference-type snapshot defaults to the same instance.

for a senior

Spot converted mutable types in review, since only collections trigger CollectionWithoutComparer, and prefer immutability, complex types or primitive collections.

for a principal

Set the team rule that value objects are immutable or mapped as complex types, so custom comparers stay rare and reviewed.

## How EF Core notices a change A tracking query hands you entities and keeps an **original-value snapshot** of every mapped property. When `SaveChanges` runs, `DetectChanges` compares each current value with its snapshot and marks differing properties as modified; only those columns go into the `UPDATE`. For `int`, `string`, `DateTime` and the other built-in types this just works: they are immutable or copied by value, and EF Core knows how to compare them. A **value converter** lets a property have a type the provider does not know, such as a `Dimensions` class turned into a string like `120x60x75` for one column. EF Core then has to compare and snapshot values of *your* type, and by default it does the simplest thing: - **comparison** uses the type's `Equals`, which for a class without an override is reference equality; - **snapshotting** copies value types, but for a reference type it stores the same instance. ## Where it goes wrong With a mutable class, the defaults miss the most natural edit: 1. A product is loaded; the snapshot of `Size` is the same `Dimensions` object the entity holds. 2. Code runs `product.Size.WidthCm = 140`. 3. At `SaveChanges`, EF Core compares the current value with the snapshot: they are one object, so they are equal. 4. No `UPDATE` is sent, and no exception tells you. Replacing the instance, `product.Size = new Dimensions { ... }`, *is* detected, which is why the bug often hides in tests. ## The three expressions `ValueComparer<T>` takes three expressions; a constructor overload without the third uses a default snapshot: | Expression | Signature | Job | |---|---|---| | equality | `Expression<Func<T?, T?, bool>>` | decide whether two values are the same, by content | | hash code | `Expression<Func<T, int>>` | produce a hash consistent with that equality | | snapshot | `Expression<Func<T, T>>` | copy a value deeply enough that later edits to the original do not reach it | They are expression trees rather than delegates because EF Core compiles them into its own change-tracking and materialization code. Equality and snapshot must agree: deep comparison is useless without a deep copy, because the snapshot would change along with the original. ## Attaching a comparer - Per property: the `HasConversion` overloads take a `ValueComparer` after the two conversion expressions, or after a `ValueConverter` instance. - Model-wide: `configurationBuilder.Properties<Dimensions>().HaveConversion<DimensionsConverter, DimensionsComparer>()` in `ConfigureConventions`, with both types as classes that have parameterless constructors. - For a key property that needs different semantics, `SetKeyValueComparer` on the mutable property metadata. ## What EF Core warns about, and what it does not Model validation logs **`CoreEventId.CollectionWithoutComparer`** when a property whose model type is a collection or other enumerable has a converter but no comparer: "Set a value comparer to ensure the collection/enumeration elements are compared correctly." A mutable non-collection class such as `Dimensions` gets **no warning**, so a code review is the only safety net. Byte arrays are a built-in special case: non-key `byte[]` properties are compared by reference, so replacing the array is detected but editing its bytes is not; key byte arrays are compared by content. ## Diagnosing a missed update When a save seems to do nothing, inspect what the change tracker believes before calling `SaveChanges`: - `db.Entry(product).Property(p => p.Size).IsModified` tells you whether EF Core saw the edit; - `db.ChangeTracker.DebugView.LongView` lists every tracked entity with its current and original values and the properties marked modified; - `db.ChangeTracker.DetectChanges()` followed by the same checks shows whether the comparer is the problem, rather than a missing `SaveChanges` call. If `IsModified` stays `false` after an in-place edit, the property's comparer and snapshot are the cause. ## Avoiding the need altogether - **Make the type immutable**: a `record` with `init` properties or a `readonly record struct`, changed with `with`. Assignment then always replaces the instance, and the defaults work. - **Map it as a complex type** instead of converting it: EF Core tracks each scalar inside, writes only changed columns, and the values stay queryable. - **Use a primitive collection** for lists of plain values; EF Core supplies element-wise comparers for them. A custom comparer is the fix for types you cannot change, for example a mutable class from a library that must be stored through a converter.

  • Why does product.Size = new Dimensions { ... } get saved without a comparer while product.Size.WidthCm = 140 does not?
    Without a comparer EF Core compares with `Equals`, which is reference equality for this class, and the snapshot is the original instance. Assigning a new object makes current and snapshot two different references, so the property is modified. Editing the loaded object changes the snapshot too, because they are the same object, so nothing differs.
  • When would you choose a complex type over a converter plus a ValueComparer for Dimensions?
    Whenever the type can be mapped: `ComplexProperty(p => p.Size)` stores width, depth and height as their own columns, tracks each one, updates only what changed and keeps them queryable in LINQ. A converter packs the values into one opaque column that queries cannot reach into. Keep the converter route for types you cannot map, such as a library type with no settable members.

A snapshot is the photocopy of a contract kept in the file. If the clerk files the original instead of a copy, every later edit lands on the 'before' version too, and comparing the two never shows a change. The snapshot expression is the photocopier.

  • EF Core deep-copies every converted reference type when it takes a snapshot.
  • Overriding Equals on a mutable class is enough for in-place edits to be detected.
  • EF Core warns at model validation about any mutable class mapped with a converter.
  • A ValueComparer is needed for every value converter, including immutable records.
  • Editing the bytes of a non-key byte[] property is detected by default.