I am now doing the following operations using a DBContext:
dbContext.SomeTables1.Add(object1) dbContext.SomeTables2.AddRange(objectArray2) dbContext.SomeTables3.AddRange(objectArray3) dbContext.SaveChanges();
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.
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?
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.
You may place an order before utilizing the Add function, then save it. Has this been tried? Would it be helpful?