三级实体结构中的Orderby()

时间:2014-08-06 19:10:19

标签: linq entity-framework

我有3个实体全部包含在一起。 MakeSource可以有ModelSourceModelSourceYearSource可以有多个var data = context.MakeSources.OrderBy(P => P.Name).Include(A => A.ModelSources .Select(B => B.YearSources)); s。我正在检索的数据如下所示:

enter image description here

到目前为止,我只能通过制作而不是模特或年份来订购。

ThenBy()

在include中添加更多OrderBy调用会引发错误。我的问题是:

如何获得由asc订购的第一批Makes的整齐排序集合,因为每个品牌的模型按升序排序,每个模型的年份按升序排序?

我尝试使用ModelSource但我无法访问var data = context.MakeSources.Include(A => A.ModelSources .Select(B => B.YearSources)).OrderBy(P => P.Name).ThenBy(p => p.ModelSources. 的嵌套属性

{{1}}

enter image description here

1 个答案:

答案 0 :(得分:0)

我在沙箱数据库中重新创建了你的情况,并写了这样的linq查询。这将为您提供品牌,型号和年份的列表。我用过汽车,但我真的不知道你的数据是什么样的。

var data = (from a in ctx.MakeSources
            join b in ctx.ModelSources on a.Id equals b.MakeSourceId
            join c in ctx.YearSources on b.Id equals c.ModelSourceId
            orderby a.Name, b.Name, c.Year
            select new { Make = a.Name, Model = b.Name, Year = c.Year }).ToArray();

这会给你一个单一的列表

要在集合中对它们进行排序,例如每个make都有一个模型集合,而模型有多年的集合,我就这样做了。

var data = (from a in ctx.MakeSources
        orderby a.Name
        select new
        {
            Make = a.Name,
            Models = (from b in ctx.ModelSources
                        where b.MakeSourceId == a.Id
                        orderby b.Name
                        select new
                        {
                            Model = b.Name,
                            Years = (from c in ctx.YearSources
                                    where c.ModelSourceId == b.Id
                                    orderby c.Year
                                    select new { ModelYear = c.Year })
                        })
        }).ToArray();

我不知道使用include和.OrderBy()的任何简单方法,因为它预加载导航属性,并且include方法中的结果必须是实体的集合,就我而言知道的。因此,返回有序列表不会加载实体(正如您收到的错误所显示的那样)

相关问题