C# / .NET Compendium PLEN
.NET / C# / Entity Framework Core

Change Tracking in EF Core - the internal mechanism

How EF Core "knows" what has changed

When you fetch an entity through a tracked DbContext, EF Core takes a snapshot of the values of all properties at the moment of fetching:

var order = await _context.Orders.FirstAsync(o => o.Id == 1);
// EF Core stores internally: { Id: 1, Status: "Pending", TotalAmount: 100 } as the "original values"

order.Status = "Shipped"; // you change a PROPERTY of the object in .NET memory, NOTHING else

await _context.SaveChangesAsync();
// The Change Tracker COMPARES the "current values" with the "original values"
// It detects: Status changed from "Pending" to "Shipped"
// Generuje: UPDATE Orders SET Status = 'Shipped' WHERE Id = 1

Entity states - EntityState

Every entity tracked by a DbContext has one of five states:

public enum EntityState
{
    Detached,   // untracked - EF Core doesn't know about it
    Unchanged,  // tracked, unchanged since it was fetched
    Added,      // nowa, do wstawienia (INSERT)
    Modified,   // zmieniona, do aktualizacji (UPDATE)
    Deleted     // marked for deletion (DELETE)
}
var order = new Order { CustomerName = "Jan" };
_context.Orders.Add(order);
Console.WriteLine(_context.Entry(order).State); // Added

var existingOrder = await _context.Orders.FirstAsync();
Console.WriteLine(_context.Entry(existingOrder).State); // Unchanged

existingOrder.Status = "Shipped";
Console.WriteLine(_context.Entry(existingOrder).State); // Modified (automatycznie!)

_context.Orders.Remove(existingOrder);
Console.WriteLine(_context.Entry(existingOrder).State); // Deleted

ChangeTracker.DetectChanges() - when it actually runs

This is a detail they sometimes ask about - change detection doesn't happen at the moment a property is set, but during certain operations:

order.Status = "Shipped"; // NIE od razu wykrywane
// DetectChanges() is called automatically on: SaveChanges(), ChangeTracker.Entries(), some LINQ on a DbSet
await _context.SaveChangesAsync(); // NOW the full snapshot vs current comparison takes place

AsNoTracking() - why it turns all this off

var readOnlyOrder = await _context.Orders.AsNoTracking().FirstAsync(o => o.Id == 1);
readOnlyOrder.Status = "Shipped"; // a change IN MEMORY, but EF Core does NOT KNOW about it

await _context.SaveChangesAsync(); // NOTHING will be saved - the entity is not tracked!

Without tracking, EF Core doesn't take a snapshot on fetching, so there is nothing to compare the current values against - which is why AsNoTracking() is faster (less memory, no comparing), but you can't modify and save changes through it.

Attach() - manually attaching an external entity to tracking

Useful when you receive an object from another DbContext (e.g. from the API layer, after deserialising from JSON) and want to update it:

public async Task UpdateOrderAsync(OrderDto dto)
{
    var order = new Order { Id = dto.Id, Status = dto.Status }; // a "detached" object, not from this DbContext

    _context.Orders.Attach(order); // attach to tracking as Unchanged
    _context.Entry(order).Property(o => o.Status).IsModified = true; // oznacz TYLKO Status jako zmieniony

    await _context.SaveChangesAsync(); // generuje UPDATE tylko dla Status
}

This lets you precisely control which specific field is to be updated, without fetching the whole entity from the database first.

Why this matters for the class vs record decision (a tie-in)

Going back to the earlier conversation about record vs class - this is exactly the technical reason why EF Core entities are almost always a class with { get; set; }, not a record with { get; init; }:

// ❌ An entity as a record with init-only properties - Change Tracking has NO WAY to work
public record Order(int Id, string Status); // init-only - can't be changed after creation!

var order = await _context.Orders.FirstAsync();
order.Status = "Shipped"; // ❌ Compile error - init doesn't allow set after creation

The Change Tracker requires mutable properties (set) to be able to register a change at all - this is a fundamental conflict with the immutability philosophy of record.

Summary of the mechanism

The Change Tracker in EF Core takes a snapshot of property values at the moment an entity is fetched through a tracked DbContext. On SaveChangesAsync() (or other DetectChanges() calls) it compares the object's current property values against that snapshot and on that basis generates the appropriate UPDATE/INSERT/DELETE. AsNoTracking() turns off creating the snapshot (faster, but with no ability to save changes), and Attach() lets you manually attach a "detached" object (e.g. from another context/layer) to tracking.

Buy me a coffee