What is the easiest way to sort an EF4 EntityCollection <T>?
I would like to add some sorting to the EntityCollection, which is bound to ItemsControl (in xaml). I would also like to make this as simple as possible. It seems like this is impossible.
If I transfer a collection to a βsortedβ version of a collection property in Entity, I lose the collection change notifications. I cannot use CollectionViewSource because the BindingListCollectionView entity collection does not support sorting for some damned reason (note: I saw a blog post with a dirty hack to get around this, so please do not reply with this, thanks).
Is there a simple way (a couple of lines of xaml line, a couple of lines of code, whatever) to achieve this?
The EntityCollection type cannot be directly filtered or sorted. This is a common LINQ-to-Entities problem, see Sorting child objects when selecting a parent using LINQ-to-Entities
One solution would be to sort the collection of entities individually using LINQ when you need data, and carry an extra performance hit. If you are working with a collection that you expect to be small and / or infrequently used, the difference in processing time may be small.
If you want the database to sort and use any indexes, you can project the main object along with the child objects. Alex James gives an example on his MSDN blog: http://blogs.msdn.com/b/alexj/archive/2009/02/25/tip-1-sorting-relationships-in-entity-framework.aspx . Of course, you are not limited to anonymous types.