DEV Community

Hasibul Islam SHaanTO
Hasibul Islam SHaanTO

Posted on

EF Core: AsNoTracking() vs AsNoTrackingWithIdentityResolution() 🔍

AsNoTracking() vs AsNoTrackingWithIdentityResolution()

Most developers know AsNoTracking() — but not everyone knows when it can silently cause bugs. Let's break down the difference and when you should be using each. 👇

⚡ AsNoTracking()

This method skips the EF Core Change Tracker completely.
The result: Faster execution, less memory usage, and great performance for read-only queries.

The catch: If two related entities point to the same row in the database (e.g., two Order records that share the same Customer), EF Core creates duplicate objects in memory instead of one shared instance.

// ⚠️ Potential memory/reference trap
var orders = dbContext.Orders
    .Include(o => o.Customer)
    .AsNoTracking()
    .ToList();

// If Order 1 and Order 2 belong to the same Customer, 
// EF Core creates TWO separate Customer objects in memory.
Enter fullscreen mode Exit fullscreen mode

🧠 AsNoTrackingWithIdentityResolution()

This gives you the same speed and memory benefits as standard no-tracking, but with one massive difference: EF Core ensures the same database row = the same object instance.

No duplicates. No weird reference bugs. This is especially useful when using .Include() on shared related entities.

// ✅ The safe way to read related data
var orders = dbContext.Orders
    .Include(o => o.Customer)
    .AsNoTrackingWithIdentityResolution()
    .ToList();

// If Order 1 and Order 2 belong to the same Customer, 
// both orders will point to the EXACT SAME Customer object in memory.
Enter fullscreen mode Exit fullscreen mode

📌 The Simple Rule Cheat Sheet

Keep this quick reference in mind for your next EF Core project:

Use Case Method to Use
Simple reads, no .Include() AsNoTracking()
Reads with related data via .Include() AsNoTrackingWithIdentityResolution()
Updating or Deleting entities Default Tracking (Don't use NoTracking)

Small detail. Big difference in correctness. 🚀

Which one do you find yourself using the most in your repositories? Drop a comment below! 👇

Top comments (0)