I'd use a Select to get the entities with OrderBy after the Where but before FirstOrDefaultAsync(). Like this:

var header = await _context.Headers
    .Include(location => location.HeaderLocation)
    .Include(details => details.Details)
    .Where(p => p.HeaderId == HeaderId)
    .Select(header => new Header
        // Assign Header values
        Location = header.Location,
        Details = header.Details.OrderBy(h => h.FieldName).OrderBy(h => h.LineVersion)


On top of the other suggestion I have seen, I used the link in the comments of the original post, and got a great answer there, too. I tested it, and it works like a charm. Here is what I ended up with:

public async Task<PermitHeader> GetPermit(int HeaderId)
    var header = await _context.Headers
            .Include(location => location.Location)
            .Where(p => p.HeaderId == HeaderId).FirstOrDefaultAsync();
    var details = await _context.Details
            .OrderBy(ob => ob.FieldName)
            .OrderBy(ob => ob.LineVersion)
            .Where(d => d.HeaderHeaderId == HeaderId).ToListAsync();
    header.Details = Details;
    return header;

Thanks for a quick response!

Related Articles