I need to get the last record from the Monitoring table
return await _context.Applications
.Include(s => s.Elements)
.ThenInclude(d => d.Monitoring.LastOrDefault())
.ToListAsync();
But EF throw an error :
System.InvalidOperationException: The expression 's.Elements.AsQueryable().LastOrDefault()' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'.
To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty').
Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations.
But when I execute the same request with OrderByDescending it works fine.
return await _context.Applications
.Include(s => s.Elements)
.ThenInclude(d => d.Monitoring.OrderByDescending(c => c.Id))
.ToListAsync();
Can anyone explain what is the difference between using OrderByDescending and LastOrDefault?
How would it be correct to get the last item in this case?