LINQ to Entities查询中出现意外结果

时间:2016-09-07 10:20:03

标签: c# entity-framework group-by linq-to-entities

我在DbContext中有以下实体:

enter image description here

我在LINQPad中编写了LINQ to Entities查询,以查找order通过的所有区域(An order将某些区域传递给某个区域,区域可能会重复):

OrderItems.Include("NominalRoutings.OperationCatalog.WorkCenter.AreaSpecification")
          .Where(x=>x.Id == 799730)
          .Select(r=>r.NominalRoutings.Where(t => t.OperationCatalog.IsActive)
                                      .Select(t=>new
                                                    {
                                                     AreaTitle=t.OperationCatalog.WorkCenter.AreaSpecification.Title,
                                                     t.ItemSequence
                                                    })
                                      .OrderBy(t => t.ItemSequence)
                               .Select(g => new{g.ItemSequence,g.AreaTitle})
                              ).FirstOrDefault()

这就是结果:

enter image description here

现在,我想找到Order传递的区域,因此我将上面的查询更改为:

OrderItems.Include("NominalRoutings.OperationCatalog.WorkCenter.AreaSpecification")
          .Where(x=>x.Id == 799730)
          .Select(r=>r.NominalRoutings.Where(t => t.OperationCatalog.IsActive)
                                      .Select(t=>new
                                                    {
                                                     AreaTitle=t.OperationCatalog.WorkCenter.AreaSpecification.Title,
                                                     t.ItemSequence
                                                    })
                                      .OrderBy(t => t.ItemSequence)
                               .GroupBy(routing => routing.AreaTitle)
                               .Select(t=>t.Key)
                              ).FirstOrDefault()

结果是:

enter image description here

但我希望得到以下结果:

  • 1 Melt
  • 2 LAB
  • 3 PU09
  • 4 LSM

因为我按ItemSequence对区域进行了排序,然后按标题对其进行了分组。我错了吗?或者我的代码有问题吗?

1 个答案:

答案 0 :(得分:0)

OrderBy会返回IOrderedEnumerable并显然会保留订单,但在使用GroupBy时,不需要保留任何订单(如果它会返回IOrderedEnumerable也是为了说清楚)。

我建议您先做GroupBy然后Order

.Select(t => new { AreaTitle = t.OperationCatalog.WorkCenter.AreaSpecification.Title, t.ItemSequence })
.GroupBy(routing => routing.AreaTitle)
.OrderBy(t => t.Min(x => x.ItemSequence))
.Select(t=>t.Key)