The mystery of order of inserts in Entity Framework
I'm trying to figure out one thing for weeks but I can't! And maybe its the first time I cannot get a straight answer from MSDN forums (by the way MSDN forums have been revamped recently. Pretty nice result. Check it out!).
Here is the scenario
I have an instance of an ObjectContext of Entity Framework, I add 6 new objects of the same type using AddObject and then SaveChanges is executed:
context.AddObject(New Person { Name = "1st" });
context.AddObject(New Person { Name = "2nd" });
context.AddObject(New Person { Name = "3rd" });
context.AddObject(New Person { Name = "4th" });
context.AddObject(New Person { Name = "5th" });
context.AddObject(New Person { Name = "6th" });
context.SaveChanges();
I would expect that the objects are inserted into database in the order they where added to the context. So I would expect to get the following result (considering that ID is an autoincrement column in database).
ID | Name
==========
1 | 1st
2 | 2nd
3 | 3rd
4 | 4th
5 | 5th
6 | 6th
But this is not what I get. Instead I get the following:
ID | Name
==========
1 | 3rd
2 | 2nd
3 | 1st
4 | 6th
5 | 5th
6 | 4th
Is this random order? I guess not! But what is it?
Important: I'm not talking about referenced data here. Just a list of flat objects that map to a single table in database.
I received some answers in MSDN forums which circulate around this argument: Why do you care?
Why do I care? First of all an end-user would expect the objects to be added in a proper order. Another reason could be that this was happening in all database access frameworks I used so far, including ADO Recordsets and ADO.NET DataAdapters etc. In any case lets say that I'm curious! Is it a secret? Don't I have the right to now how my data will be inserted to database?
I also got some suggestions which try to go around the problem (perform SaveChanges after each Add etc).

Comments [0]