What logic determines the insert order of Entity Framework 6

c# entity-framework entity-framework-6 entity-framework-core


I am now doing the following operations using a DBContext:


The database records are not inserted by the EF in this sequence; rather, they are inserted in a random manner. I have to do a to insert them in the same sequence.dbContext.SaveChanges() after each addition. This is not a practical method; in my situation, it takes 10 seconds to complete all of my inserts, compared to 3 seconds for a random order with one save.

Note that I need the proper sequence to break a stalemate.

My inquiries are:

  • Is this issue resolved in EF7?
  • I can profile EF and determine the random order, however, is there a guarantee that it will be consistently with the same random order or does it change between requests? (I can adopt my other code if the answer to this question is positive).
  • Is there a better way of maintaining the order than dbContext.SaveChanges() on every addition?
1/14/2016 5:09:50 PM

Accepted Answer

  • In EF6 or EF7, there is no ability to set a save order.
  • Since this is not a problem, the issue is not rectified in EF7.
  • If the predecessor is the same, the order will remain the same (which will likely rarely happen)

When you use SaveChanges, all entities are sorted again by the method "TryTopologicalSort," which loops to add commands with no predecessors remaining, after being sorted from an internal order in the method "oeProduceDynamicCommands" (if you add A and B and A depend on B, then B will be inserted before A)

The last task is batch adding of inserts.

Since you need 3 seconds to conduct your insert, I'll presume you have thousands of entities. Bulk inserting might enhance your performance and cut down on the 10 seconds, and perhaps even the first 3 seconds!

Two libraries I can suggest are listed below:

I'm the project owner for the Entity Framework Extensions, Disclaimer.

8/22/2018 10:17:09 PM

Popular Answer

You may place an order before utilizing the Add function, then save it. Has this been tried? Would it be helpful?

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow