Linq排序父母和孩子

时间:2019-04-30 23:50:43

标签: c# entity-framework linq entity-framework-core

是的,关于使用Linq查询选择和排序父母和孩子,在线上有200万个问题和答案,但是我还没有找到这个简单用例的答案。

FWIW,我正在EF Core中做到这一点。

我有包括SortIndex属性的父子实体:

public class Parent {
  public int Id { get; set; }
  public int SortIndex { get; set; }
  public string Name { get; set; } // Some other property(s)

  // Navigation properties
  public List<Child> Children { get; set; }
}

public class Child {
  public int Id { get; set; }
  public int SortIndex { get; set; }
  public string Name { get; set; } // Some other property(s)

  // Navigation properties
  public int ParentId { get; set; }
  public Parent Parent { get; set; }
}

我试图弄清楚如何返回“父母”的集合,并能够导航到每个父母的“孩子”。并且我希望父母和孩子按照各自的SortIndex属性进行排序

根据Microsoft docs,我可以构造一个Linq查询,该查询返回带有.Include()语句的(排序的)父母和相关的(未排序的)孩子(通过“渴望加载”),像这样:

var parents = context.Parents
              .Include(p => p.Children)
              .OrderBy(p => p.SortIndex);

或使用C#Linq语法:

var parents = from p in context.Parents
                .Include(x => x.Children)
              orderby p.SortIndex
              select c;

但是,如何添加一个子句,按其SortIndex属性对渴望加载的子级进行排序?

0 个答案:

没有答案
相关问题