简体   繁体   中英

C# Entity Framework - Order by Children of Children

I am failing at using OrderBy() on the child of a child.

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. After sorting, there are 0 items. 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 ). Consider using .Select() instead of your 2 .OrderBy() .

You could also just write: ThenBy(e => e.Jobs) and make sure your Job class implements the IEqualityComparer interface

Can't use an order by inside an order by

try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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