'OrderBy in Include child using EF Core [duplicate]

In my .NET Core / EF Core application I have a model with a nested list of child objects. When I retrieve an instance, I need the nested list to be ordered by one of the child's properties.

What is the correct way to sort this list so that it always returns sorted correctly from my database?

Right now I do it after loading from database:

public async Task<Parent> GetParent(int id)
{
    var result = await context.Parents
        .Include(p => p.Children)
        .SingleOrDefaultAsync(p => p.Id == id);

    result.Children = result.Children.OrderBy(c => c.Sequence).ToList();

    return result;
}


Solution 1:[1]

The result you are trying to return is the ordered list of children. That's not what you want. Instead sort the children then return the parent:

public async Task<Parent> GetParent(int id)
{
    var parent = context.Parents
        .Include(p => p.Children)
        .SingleOrDefaultAsync(p => p.Id == id);

    parent.Result.Children = parent.Result.Children.OrderBy(c => c.Sequence).ToList();

    return await parent;
}

Solution 2:[2]

var result = loadedInMemory.Result.Children.OrderBy(c => c.Sequence).ToList();

You need to add ToList() at the end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 see sharper
Solution 2 Günter Zöchbauer