You execute a method from the Entity Framework Extensions library, and the following error is thrown:
And you use a code similar to this:
One cause could be simply a wrong save order provided by either Entity Framework or EFE Library.
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.
- ADD the line AutoDectectChangesEnabled = true; before BulkSaveChanges
- CALL ctx.ChangeTracker.DetectChanges();
- REMOVE the line AutoDetectChangesEnabled = false;