6

Does the Entity Framework 4 have ordered collections?

For example my Order has a property that is a collection of OrderItems, but the order is important and I would rather not sort them before I access them.

See Nhibernate for an example: List vs Set vs Bag in NHibernate

Community
  • 1
  • 1
Adam Gordon Bell
  • 3,083
  • 2
  • 26
  • 53

1 Answers1

4

It doesn't. You can force an order in a couple of ways however :

This answer explains one EF4 LINQ Ordering Parent and all child collections with Eager Loading (.Include()) (kind of)

More simply, if you are querying a single order, you can do so with the orderlines ordered in a specifc way:

var thing = _repo.GetOrder(id)
 .Select(item => 
    new { item, ord = item.orderlines.OrderBy(o => o.orderbythis) }
    ).FirstOrDefault().item;
Community
  • 1
  • 1
Andiih
  • 12,285
  • 10
  • 57
  • 88
  • keep in mind this will return an "item" without the "ord" - you havent't assigned the "ord" anonymous property back into the projected type. – RPM1984 Jan 14 '11 at 23:19
  • Yes I know. However item.orderlines IS ordered in the specified manner. I guess there is a danger this may break in future releases, but it does work! If anyone can explain why this works I'd love to know! – Andiih Jan 15 '11 at 12:13