What's the easiest way to sort an EF4 EntityCollection<T>?
Asked Answered
B

1

7

I'd love to add some sorting to an EntityCollection that is bound to an ItemsControl (in xaml). I'd also like to do it as simply as possible. It appears that this is not possible.

If I wrap the collection in a "sorted" version of the collection property within the Entity I lose collection change notifications. I can't use a CollectionViewSource because the entity collection's BindingListCollectionView does not support sorting for some goddamned reason (note: I've seen the blog post with the "dirty" hack to get around this, so please don't answer with that kthx).

Is there a simple (couple lines of xaml, couple lines of code, whatever) way to achieve this??

Bayne answered 16/5, 2010 at 20:45 Comment(0)
W
3

The EntityCollection type cannot be directly filtered or sorted. It's a common LINQ-to-Entities problem, see: Sort child objects while selecting the parent using LINQ-to-Entities

One solution would be to sort the entity collection separately using LINQ when you need the data, and incur the additional performance hit. If you're working with a collection you expect to be small and/or infrequently used, the difference in processing time could be negligible.

If you want the database perform the sorting and make use of any indexes, you can project the main entity along with the child entities. Alex James posts an example in his MSDN blog: http://blogs.msdn.com/b/alexj/archive/2009/02/25/tip-1-sorting-relationships-in-entity-framework.aspx. You're not limited to anonymous types, of course.

Whiggism answered 27/7, 2011 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.