Sort child objects while selecting the parent using LINQ-to-Entities
c#, linq, linq-to-entities
Solution
Alex James discusses this issue in this tip.
Essentially, relationships are considered as unordered, per standard relational modeling. So you can't get them sorted. But you can project onto other collections, which can be sorted.
Problem
Imagine you've got some Entity Framework entities that look like this (obviously not these specific classes, but the autogenerated ones with all the Entity Framework plumbing; these are just for illustration): ``` public class Parent { public int ID { get; set; } public List<Child> Children { get; set; } } public class Child { public int ID { get; set; } public Parent Parent { get; set; } public int Number { get; set; } } ``` I have a LINQ query that looks like this: ``` from parent in context.Parents.Include("Child") select parent ``` However, this returns a list of Parents where the children are in ID order. I want the children to be sorted by their Number property within their Parent. How can this be done? Edit: A clarification: the idea is to have the query hidden behind a method call (in the layer facade) that simply returns an `IList<Parent>`. This makes using solutions like anonymous class queries and manual sorting painful (compared to some panacea solution where you can just do it in the query or something).