Foreign Key Constraint + AutoDectectChanges Disabled


You execute a method from the Entity Framework Extensions library, and the following error is thrown:

And you use a code similar to this:

using (var ctx = new MyEntities())
	ctx.Configuration.AutoDetectChangesEnabled = false;



One cause could be simply a wrong save order provided by either Entity Framework or EFE Library.

Cause Source

The main reason that could cause this issue is disabling AutoDetectChanges and not enabling it before the SaveChanges/BulkSaveChanges.

When the AutoDetectChanges is disabled, there is no check about the relationship, and that could cause sometime the Item to be added before a new Category (Which should be added first)! Leading to the Foreign Key issue.

In additional, there is no reason why this code should disable DetectChanges. Since the AddRange method is used, the “DetectChanges” method is called only once per AddRange call, so don’t suffer from a performance issue.


  1. ADD the line AutoDectectChangesEnabled = true; before BulkSaveChanges
  2. CALL ctx.ChangeTracker.DetectChanges();
  3. REMOVE the line AutoDetectChangesEnabled = false;