OrderBy in Include child using EF Core

c# entity-framework-core

Question

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. I understand from reviewing similar questions and reported issues on EF Core that I can't order the nested list on retrieving the instance. So now I am trying to sort it once loaded in memory. but here I am also not successful.

I am using a Repository Pattern to access DbContext.

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

Latest I tried:

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

        var result = loadedInMemory.Result.Children.OrderBy(c => c.Sequence);
        // When I order within the Task<Parent>, result becomes IOrderedEnumerable 
        // and I can't return it.

        return await result;
    }
1
3
2/25/2019 3:25:31 AM

Accepted Answer

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;
}
3
2/25/2019 3:33:52 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow