简体   繁体   中英

Sort child objects while selecting the parent using LINQ-to-Entities

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).

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.

Take a look at this post . You could try something like this:

var query = ((from parent in context.Parents
              from child in parent.Child
              orderby child.Number ascending
              select parent) as ObjectQuery<Parent>
            ).Include("Child");

One option is executing the query and sorting in memory (eg on output).

var parents = context.Parents.Include("Child").ToList(); //note that ToList is here just to execute the query and get the objects in memory

foreach (var p in parents)
{
   //do something with parent item
   foreach (var c in p.Child.OrderBy(c => c.Number))
   {
      /do something with the child item
   }
}

There are two other options that also seem to work with their own pros and cons:

LINQ ".Include" orderby in subquery

LINQ OrderBy Name ThenBy ChildrenCollection.Name

here is something that I have done:

var query = from parent in context.Parents 
            select new 
            {
                 parent,
                 childs = from child in context.Child
                            orderby child.ID ascending
                            select new
                            {
                                 child
                            }
            }

I implememented something like this and it worked very well for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM