Home > database >  C# Entity Framework - Order by Children of Children
C# Entity Framework - Order by Children of Children

Time:07-27

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 View

CodePudding user response:

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

CodePudding user response:

Can't use an order by inside an order by

try

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