HeadlinesBriefing favicon HeadlinesBriefing.com

EF Core Tracking Pitfalls: Avoid Duplicate Keys

DEV Community •
×

EF Core ships with change tracking enabled by default. In production, queries pile up tracked entities, inflating memory and GC pressure. When traffic spikes, teams flip the global NoTracking flag to tame the heap, only to see random duplicate‑key violations erupt in unrelated code paths. The fix feels instant, but the root cause remains hidden.

Change tracking builds an identity map, tracks state, and maintains relationships. When entities are detached, EF treats them as new, generating INSERTs that collide with existing rows. A detached entity also triggers a silent no‑op on SaveChanges, leaving developers unaware of the failure. Understanding this behavior is key to avoiding silent bugs.

The practical cure is to separate read and write concerns. Read‑only repositories should always use NoTracking, while write repositories keep tracking enabled and rely on Attach or Update only when appropriate. This pattern eliminates accidental inserts, preserves relationship integrity, and makes performance predictable across scaling.