In this lesson, you will learn how Entity Framework Core monitors your objects to determine exactly which database commands to execute during SaveChanges().
The Snapshot Mechanism
When you query an entity from the database, EF Core doesn't just hand you the object; it creates an internal snapshot of the entity's original values. This snapshot acts as a baseline, representing the entity exactly as it looked when it was first retrieved from the database.
As you modify properties in your code, EF Core’s ChangeTracker periodically compares the current values of the entity against that initial snapshot. This comparison happens primarily when you call SaveChanges() or manually invoke ChangeTracker.DetectChanges().
Tracking States
Every entity managed by the DbContext is assigned one of five specific states:
- Unchanged: The entity is identical to the database snapshot.
- Added: The entity is new and needs an
INSERTcommand. - Modified: At least one property differs from the snapshot, requiring an
UPDATE. - Deleted: The entity is marked for removal, requiring a
DELETE. - Detached: The entity is not being tracked by the context.
Consider this workflow:
var user = context.Users.Find(1); // State: Unchanged
user.Email = "new@example.com"; // Change detected on next SaveChanges()
context.SaveChanges(); // EF Core compares current vs snapshot, generates UPDATE
Why It Matters
By maintaining these states, EF Core performs Change Tracking, which is highly efficient. Instead of updating every column in a row, EF Core generates SQL that only includes the specific properties that have actually changed. If no properties have changed, EF Core realizes the entity is still Unchanged and skips the database round-trip entirely, saving performance and reducing contention.
While this background magic makes development seamless, keep in mind that tracking adds a small memory overhead. For high-performance read-only scenarios, you might eventually use .AsNoTracking() to bypass this mechanism, but for standard CRUD operations, the state tracker is your best friend for generating precise, minimal SQL commands.
Key Takeaway: EF Core uses an internal snapshot of your entities to calculate the "delta" between the original data and your modifications, ensuring only necessary SQL commands are executed.