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;
}
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;
}