简体   繁体   English

C# 实体框架 - 按Children of Children 排序

[英]C# Entity Framework - Order by Children of Children

I am failing at using OrderBy() on the child of a child.我在孩子的孩子上使用 OrderBy() 失败。

IQueryable<Conteso.Data.Models.Employee> query 
    = _context.Employee
              .Include(e => e.Person)
              .Include(e => e.Jobs).ThenInclude(j => j.EmployeeType)
              .Include(e => e.Jobs).ThenInclude(j => j.Absences).ThenInclude(a => a.AbsenceType)
              .Where(e => e.Jobs.Any(j => j.Absences.Count > 0));

Before sorting, there are many records in the Results View.排序前,Results View 中有很多记录。 After sorting, there are 0 items.排序后,有 0 个项目。 Here is my attempt at sorting.这是我的排序尝试。

    query = query.OrderBy(e => e.Person.LastNameFirst)
                 .ThenBy(e => e.Jobs.OrderBy(j => j.Absences.OrderBy(a => a.Date)));

SQL 视图

I think your issue is that you're not selecting a key from your ThenBy (more info here: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.thenby?view=net-6.0 ).我认为您的问题是您没有从ThenBy中选择密钥(更多信息: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.thenby?view=net -6.0 )。 Consider using .Select() instead of your 2 .OrderBy() .考虑使用.Select()而不是你的 2 .OrderBy()

You could also just write: ThenBy(e => e.Jobs) and make sure your Job class implements the IEqualityComparer interface您也可以只写: ThenBy(e => e.Jobs)并确保您的 Job class 实现IEqualityComparer 接口

Can't use an order by inside an order by不能在 order by 中使用 order by

try尝试

query = query.OrderBy(e => e.Person.LastNameFirst)
             .ThenBy(e => e.Jobs.Absences.Date);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM