排序孩子,而选择使用父对象LINQ到实体 [英] Sort child objects while selecting the parent using LINQ-to-Entities

查看:163
本文介绍了排序孩子,而选择使用父对象LINQ到实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,你有一些看起来像这样的实体框架实体(显然不是这些具体的类,但自动生成的那些所有的实体框架管道,这些都只是为了举例说明):

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; }
}



我有一个LINQ查询,看起来像这样:

I have a LINQ query that looks like this:

from parent in context.Parents.Include("Child")
select parent

不过,这将返回那里的孩子都在ID顺序家长的列表。我想孩子们被他们的父母在他们的数字属性进行排序。 ?
如何才能做到这一点。

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?

修改:一种澄清:这个想法是有查询隐藏在方法调用的背后(在简单地返回一个的IList<层门面);家长和GT; 。这使得使用解决方案,如匿名类的查询和人工分拣痛苦(比起一些灵丹妙药解决方案,在那里你可以做到这一点在查询或东西)。

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.

这篇关于排序孩子,而选择使用父对象LINQ到实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆