Shrewdroid
Shrewdroid

Reputation: 800

Save Entities in a Specific Order

I am using Entitiy Framework and have come across a weird problem. I am trying to save a collection to the database (say: Collection of Rounds). Now each item in this collection in turn has a collection of child elements (say: Collection of Events).

Which would look something like this:

Round 1
    (No Child Elements)
Round 2
    Event 1
    Event 2
    Event 3
Round 3
    (No Child Elements)
Round 4
    Event 1
    Event 2

As shown above it is not necessary that the parent object will always have a child collection.

Now here is the problem: My requirement is that i want to save the data as i have added it to the collection. But, while saving EF saves the items having a child collection first and so the order is modified upon saving. So, in the database Round 2 is saved first and then others are saved randomly.

Is there any way to force EF to save the Rounds collection in the order that i have constructed it?? It should always save starting from Round 1 and should end with saving Round 4.

Thanks guys : )

Upvotes: 0

Views: 2570

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

Neither database or EF guarantees ordering. In the same way if you query the database you don't have to get elements in expected order. If you want exact order you must add additional column to keep record's ordering value and use OrderBy extension method when retrieving data.

Order of operations executed by SaveChanges is in full control of EF. You cannot change it.

Upvotes: 4

Related Questions