使用 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屋!