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

女生的网名这么多〃 提交于 2020-01-15 01:23:10

问题


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


回答1:


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.




回答2:


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");



回答3:


One option is executing the query and sorting in memory (e.g. 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




回答4:


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



来源:https://stackoverflow.com/questions/1854732/sort-child-objects-while-selecting-the-parent-using-linq-to-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!