实体框架使用排序顺序加载子集 [英] Entity Framework loading child collection with sort order
问题描述
与引用问题的autor相反我尝试加载孩子总是排序。所以如果我加载一个父实例我期望,子集合按排序顺序排序。如何使用Code First Fluent API和POCO来实现此行为?
提示:在孩子集合中调用.Sort(...)不是一个选择。
您无法直接实现它,因为EF中的加载或延迟都不支持排序或过滤。
您的选项是:
- 从数据库加载应用程序之后对数据进行排序
- 执行单独查询以加载子记录。一旦您使用单独的查询,您可以使用
OrderBy
第二个选项可以用于显式加载:
var parent = context.Parents.First(...);
var entry = context.Entry(parent);
entry.Collection(e => e.Children)
.Query()
.OrderBy(c => c.SortOrder)
.Load();
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.
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?
Hint: It's not an option to call .Sort(...) on the child collection.
You cannot achieve it directly because neither eager or lazy loading in EF supports ordering or filtering.
Your options are:
- Sort data in your application after you load them from database
- Execute separate query to load child records. Once you use separate query you can use
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();
这篇关于实体框架使用排序顺序加载子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!