skip to content

In EF Core 10, how do notification-based change tracking strategies differ from snapshot tracking, and what do they require of entity classes?

level: seniorimportance: nice to knowfreq 14%

answer

  1. ChangeTrackingStrategy enum
  2. INotifyPropertyChanging and INotifyPropertyChanged
  3. INotifyCollectionChanged on collections
  4. HasChangeTrackingStrategy on ModelBuilder
  5. UseChangeTrackingProxies and CreateProxy

basics

~20 s

Snapshot tracking copies values and needs DetectChanges to find edits. Notification strategies make entities raise INotifyPropertyChanged (and optionally INotifyPropertyChanging) so EF Core learns of each edit immediately; collections must implement INotifyCollectionChanged, and the strategy is opted into with HasChangeTrackingStrategy.

solid answer

~30 s

`ChangeTrackingStrategy.Snapshot` is the default: EF Core snapshots values and needs `DetectChanges` to find edits. `ChangedNotifications` needs `INotifyPropertyChanged`; edits are reported immediately, but EF Core still snapshots original values. `ChangingAndChangedNotifications` also needs `INotifyPropertyChanging`, so EF Core records the old value just before the change and keeps no snapshot - most original values are then unavailable. `ChangingAndChangedNotificationsWithOriginalValues` uses both events and still keeps originals. Collection navigations must implement `INotifyCollectionChanged` (`ObservableCollection<T>` or EF Core's `ObservableHashSet<T>`). EF Core does not hook these events on its own: you opt in with `modelBuilder.HasChangeTrackingStrategy(...)`, or let `UseChangeTrackingProxies()` from `Microsoft.EntityFrameworkCore.Proxies` generate notifying subclasses, created with `CreateProxy<T>()`.

code

csharp · 14 lines
csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasChangeTrackingStrategy(
        ChangeTrackingStrategy.ChangingAndChangedNotificationsWithOriginalValues);
}

// or let the Proxies package generate notifying subclasses
builder.Services.AddDbContext<CrmDbContext>(o => o
    .UseNpgsql(connectionString)
    .UseChangeTrackingProxies());

var lead = db.CreateProxy<Customer>(); // not new Customer()
lead.Name = "Grace Hopper";
db.Customers.Add(lead);

go deeper

for a junior

Know that EF Core's default is snapshot tracking and that another option exists where entities report their own changes.

for a middle

Name the interfaces each strategy needs, why collections must notify, and that the strategy must be configured rather than inferred.

for a senior

Recognise when DetectChanges cost justifies notification entities or proxies, and the consequences for original values and for creating new entities.

for a principal

Weigh event plumbing, proxy constraints and lost original values against scan cost before letting a team move a model off snapshot tracking.

## Two ways to learn that something changed EF Core has to know which property values changed before it can build an `UPDATE`. There are two broad mechanisms: - **Snapshot tracking** (the default): EF Core copies every property value when an entity is tracked and later compares current values with that copy in `DetectChanges`. Entities can be plain classes. - **Notification tracking**: the entity itself raises an event whenever a property or collection changes, and EF Core reacts at that moment. No scan is needed to find edits. The choice is expressed with the `ChangeTrackingStrategy` enum. ## The four strategies | `ChangeTrackingStrategy` | Interfaces the entity needs | Needs `DetectChanges` | Snapshots original values | |---|---|---|---| | `Snapshot` | none | yes | yes | | `ChangedNotifications` | `INotifyPropertyChanged` | no | yes | | `ChangingAndChangedNotifications` | `INotifyPropertyChanged` and `INotifyPropertyChanging` | no | no | | `ChangingAndChangedNotificationsWithOriginalValues` | both | no | yes | With `ChangingAndChangedNotifications`, EF Core captures the old value from the *changing* event just before it is overwritten, so it does not need a snapshot at tracking time. The price is that original values are **not recorded for most properties**: asking for one throws an `InvalidOperationException` whose message suggests `ChangingAndChangedNotificationsWithOriginalValues` instead. ## What the entity classes must do 1. Implement the interfaces the strategy names, and raise `PropertyChanging` before and `PropertyChanged` after **every** mapped property and navigation change, not only the ones a UI binds to. 2. Use collection types that implement `INotifyCollectionChanged` for collection navigations: `ObservableCollection<T>`, or EF Core's `ObservableHashSet<T>`, which looks up faster but does not keep a stable order. 3. Configure the strategy. EF Core cannot verify that every setter raises its events, so it does **not** subscribe automatically just because the interfaces are there. Call `modelBuilder.HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangingAndChangedNotifications)` in `OnModelCreating`. EF Core does check the shape: configuring a notification strategy on a type that lacks the required interface is rejected, and tracking an entity whose collection navigation does not implement `INotifyCollectionChanged` throws an `InvalidOperationException` that suggests `ObservableCollection<T>`. It cannot catch a setter that forgets to raise its event - that edit is simply missed. `EntityTypeBuilder.HasChangeTrackingStrategy` sets the strategy per entity type, but the docs call that usually counterproductive: as long as some types still use snapshots, `DetectChanges` still has to run for them. ## Letting EF Core write the boilerplate: change-tracking proxies The `Microsoft.EntityFrameworkCore.Proxies` package (built on Castle.Core) can generate a subclass of each entity at runtime that overrides the property setters and raises the events for you: - enable it with `options.UseChangeTrackingProxies()`; the proxy convention then applies `ChangingAndChangedNotifications` to the model; - entity classes must be inheritable and their properties `virtual`; - EF Core creates proxies itself when it materializes query results, but **new** entities must be created with `context.CreateProxy<Customer>()` (or the `DbSet<T>` overload), not with `new`, or they will not notify. ## When it is worth it - **Keep snapshots** for a typical web API: contexts are short-lived, few entities are tracked per request, and `DetectChanges` is cheap. - **Consider notifications** when one context tracks very many entities and makes many edits before saving - a long-running desktop data-binding screen or a large in-memory editing session - so the repeated scans would cost more than the event plumbing. - **Know the costs**: more entity code or a proxy dependency, `virtual` members, `CreateProxy` for new objects, and fewer original values unless you choose the `WithOriginalValues` variant.

  • Your entities implement INotifyPropertyChanged for a WPF screen, but EF Core still runs DetectChanges. Why?
    Implementing the interface is not enough: EF Core subscribes only when the model is configured for a notification strategy, for example with `HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangedNotifications)`. EF Core cannot check that every property raises the event, so it leaves the default snapshot strategy in place until you opt in.
  • After switching to ChangingAndChangedNotifications, code that reads OriginalValues for an audit log throws. What happened?
    That strategy keeps no snapshot, so original values are not recorded for most properties, and reading one throws an `InvalidOperationException`. Use `ChangingAndChangedNotificationsWithOriginalValues`, which still uses notifications for detection but keeps original values.

Snapshot tracking is an auditor who photocopies every form when it is filed and later compares each page with the copy. Notification tracking is a clerk who phones the auditor the moment any field is edited: nothing to compare later, but every clerk must remember to call, and one who forgets means a missed edit.

  • EF Core subscribes to INotifyPropertyChanged as soon as an entity implements it.
  • ChangedNotifications stops EF Core from storing original-value snapshots.
  • Change-tracking proxies work for new entities created with the new operator.
  • Setting a notification strategy on one entity type removes DetectChanges for the whole context.
  • Notification tracking is the recommended default for ASP.NET Core APIs.