Entity Framework ObservableCollection Add Method - Unexpected Behavior

The documentation for Collection<T>.Add specifically states that when calling the Add method, the new item is appended to the end of the collection. This is not necessarily true. I haven't tested it in all it's incarnations yet but it appears to be adding to the beginning (index 0) of my collection.

http://msdn.microsoft.com/en-us/library/ms132404(v=VS.100).aspx 

My Entity Framework Self-Tracking object contains a collection of items. In my tests I created a couple of dummy objects and inserted them into the database. I was surprised to find that they were in reverse order! The collection type, by the way, is System.Collections.ObjectModel.ObservableCollection<T> in a Silverlight 4 application.

When I looked at the values in the immediate window, sure enough the first item in the collection was the last item I added and so on up the chain. Now you should never count on sorting your database items based on an identity key (obviously) but for spot check purposes, when I'm looking directly at the raw data, I prefer to have my items put in the database in the order expected.

So now rather than calling the Add() method, I'm switching over to using the Insert() method. As a perfomance point though, wouldn't adding an item to the beginning of an array be inherently more processor intensive than adding it to the end?

 

No Comments