My question assumes simple inserts into a table with no relevant relations.
// various unrelated operations w/context...
var one = new DbRecord();
var two = new DbRecord();
var thr = new DbRecord();
context.DbRecords.Add(one);
context.DbRecords.Add(two);
context.DbRecords.Add(thr);
// various unrelated operations w/context...
context.SaveChanges();
In this case, will my DbRecord entities always be inserted in the order I added them to the DbSet? They seem to be in my testing, but can I rely on this?
“various unrelated operations” refers to operations on different, not-related DbSets of the same context; inserts, deletes, and updated entities (POCOs, in my case)
I want them to be inserted in exact order so I can use the pk/identity field to sort by, yet I also need to take advantage of the implicit transaction that the context provides around my context.SaveChanges(). Although the other operations are not related as far as the database schema is concerned, the entries themselves are essentially log entries about the updates being performed, and their order is critical.
If the context does not guarantee inserting the records in the same order, I will have to add a datetime field to the records, and handle rolling back myself.
This is not guaranteed according to the documentation. This means, that you cannot rely on this behavior. Basically, it comes down to the questions whether you are willing to take the risk that…
Answering these questions is up to you. Usually, the answer should be “no”.
If your testing comes up ok, this does not mean that the “unrelated actions” your were talking about don’t cause any disturbance in rare situations. This is a silent bug that nobody will notice during testing.