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;
}
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With