使用EF Core的“包含子项"中的OrderBy [英] OrderBy in Include child using EF Core
问题描述
在我的.NET Core/EF Core应用程序中,我有一个带有嵌套子对象列表的模型.检索实例时,我需要按孩子的属性之一对嵌套列表进行排序.通过查看类似问题并在EF Core上报告问题,我了解到我无法在检索实例时对嵌套列表进行排序.因此,现在尝试将其加载到内存后对其进行排序.但是在这里我也不成功.
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.
我正在使用存储库模式来访问DbContext.
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?
我最近尝试过:
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;
}
这篇关于使用EF Core的“包含子项"中的OrderBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!