实体框架按排序顺序加载子集合
我有两个表,一个父表和一个子表.子表有一个列 sortorder(一个数值).由于 EF 缺少支持 IList 包含排序顺序而不公开排序顺序(请参阅:实体框架持久化子集合排序顺序) 我的子类也有一个属性 SortOrder,这样我就可以按照排序顺序存储子类.
I have two tables a parent and a child table. The child table has a column sortorder (a numeric value). Because of the missing support of the EF to persist a IList inclusive the sort order without exposing the sortorder (see: Entity Framework persisting child collection sort order) my child class has also a property SortOrder, so that i can store the children with the sort order.
与引用问题的作者相反,我尝试加载总是排序的孩子.因此,如果我加载我期望的父实例,则子集合按排序顺序排序.如何使用 Code First Fluent API 和 POCO 实现这种行为?
In contrast to the autor of the referenced question i try to load the children always sorted. So if i load a parent instance I expect, that the child collection is sorted by sort order. How can i achieve this behaviour with the Code First Fluent API and POCO's?
提示:在子集合上调用 .Sort(...) 不是一个选项.
Hint: It's not an option to call .Sort(...) on the child collection.
你不能直接实现它,因为 EF 中的预先加载或延迟加载都不支持排序或过滤.
You cannot achieve it directly because neither eager or lazy loading in EF supports ordering or filtering.
您的选择是:
- 从数据库加载数据后对应用程序中的数据进行排序
- 执行单独的查询以加载子记录.使用单独的查询后,您可以使用
OrderBy
第二个选项可以与显式加载一起使用:
The second option can be used with explicit loading:
var parent = context.Parents.First(...);
var entry = context.Entry(parent);
entry.Collection(e => e.Children)
.Query()
.OrderBy(c => c.SortOrder)
.Load();