【发布时间】:2018-12-27 21:04:37
【问题描述】:
我有一个具有深度嵌套类层次结构的用例,例如:
public class Parent
{
public int Id { get; set; }
public List<ChildOne> Children { get; set; }
}
public class ChildOne
{
public int Id { get; set; }
public int ParentId { get; set; }
public List<ChildTwo> ChildrenTwo { get; set; }
}
public class ChildTwo
{
public int Id { get; set; }
public int Priority { get; set; }
public int ChildOneId { get; set; }
public List<ChildThree> ChildrenThree { get; set; }
}
public class ChildThree
{
public int Id { get; set; }
public int ChildTwoId { get; set; }
}
如果我想加载所有父对象及其相关的子级别,我会这样做:
var objects = context.Parent
.Include(parent => parent.Children)
.ThenInclude(childOne => childOne.ChildrenTwo)
.ThenInclude(childTwo => childTwo.ChildrenThree)
.ToList();
但是,如果我希望 ChildOne 的即时加载导航属性中的 ChildrenTwo 实体按其 Priority 排序怎么办?我已经做了一些研究,从下面的链接(和其他一些链接)来看,显然在 EF Core 中还不能直接实现:
- https://github.com/aspnet/EntityFrameworkCore/issues/9445
- https://github.com/aspnet/EntityFrameworkCore/issues/2919
- https://github.com/aspnet/EntityFrameworkCore/issues/9067
那么,您如何以一种快速的良好/干净的方式实现上述ChildrenTwo(由Priority)的排序?这可能意味着大部分工作应该发生在 DB 服务器上,而不是 .NET 客户端。这里最好的方法是什么?
【问题讨论】:
-
仅通过将 (
select new { ... }) 投影到 DTO 或原始实体类,在必要的 LINQ 语句中应用排序。 -
@GertArnold 感谢您的回复。我不确定我是否完全理解 - 你能举个例子吗?