What logic determines the insert order of Entity Framework 6

  • There is no way you can specify a save order in EF6 or EF Core (initially named EF7).
  • The issue is not resolved in EF Core (initially named EF7) since this is not an issue.
  • The order will be the same if the predecessor is the same (which will likely rarely happen)

When you call SaveChanges, all entities are ordered from an internal order in the method “ProduceDynamicCommands” then sorted again by the method “TryTopologicalSort” which loops to add command with no predecessor left (if you add A and B and A depend on B, then B will be inserted before A)

You are left to insert by batch addition.

Since it takes you 3 seconds to perform your insert, I will assume you have thousands of entities and performing bulk insert may improve your performance to reduce the 10 seconds to less, and then maybe the initial 3 seconds!

Here are 2 libraries I can recommend:

  • https://efbulkinsert.codeplex.com/
    • FREE but doesn’t work with all kind of associations and inheritances
  • http://entityframework-extensions.net/
    • PAID but support everything

Disclaimer: I'm the owner of the Entity Framework Extensions project.


I've found a way to do it. It just thought I'd let you know:

using (var dbContextTransaction = Context.Database.BeginTransaction())
{
   dbContext.SomeTables1.Add(object1);
   dbContext.SaveChanges();

   dbContext.SomeTables1.Add(object2);
   dbContext.SaveChanges();

   dbContextTransaction.Commit();
}