Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 894
Superman.Lopez Avatar asked Feb 25 '19 03:02

Superman.Lopez


2 Answers

Starting with Entity Framework Core 5.0, you can sort (OrderBy) and filter (Where) directly in the Include statement (with some restrictions). See the Microsoft Documentation.

Your statement can therefore be simplified like this:

    public async Task<Parent> GetParent(int id)
    {
        return await context.Parents
            .Include(p => p.Children.OrderBy(c => c.Sequence))
            .SingleOrDefaultAsync(p => p.Id == id);
    }

This is a nice step forward for EF Core in my opinion.

like image 148
Kolazomai Avatar answered Nov 16 '22 01:11

Kolazomai


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;
}
like image 30
see sharper Avatar answered Nov 16 '22 01:11

see sharper