在EF 4.1 Code-First中使用Include和/或Select方法时,如何对导航属性进行排序? [英] Order navigation properties when using Include and/or Select methods with EF 4.1 Code-First?

查看:408
本文介绍了在EF 4.1 Code-First中使用Include和/或Select方法时,如何对导航属性进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这里解释的问题的第二步: @Slauma 的指导下,我已成功使用以下方法检索数据:

This is the second step of a question explained here: EF 4.1 code-first: How to load related data (parent-child-grandchild)?. With @Slauma's guidance, I have successfully retrieved data with this approach:

var model = DbContext.SitePages
    .Where(p => p.ParentId == null && p.Level == 1)
    .OrderBy(p => p.Order) // ordering parent 
    .ToList();

foreach (var child in model) { // loading children
    DbContext.Entry(child)
        .Collection(t => t.Children)
        .Query()
        .OrderBy(t => t.Order) // ordering children
        .Load();

    foreach (var grand in child.Children) { // loading grandchildren
        DbContext.Entry(grand)
            .Collection(t => t.Children)
            .Query()
            .OrderBy(t => t.Order) // ordering grandchildren 
            .Load();
    }
}

尽管这种方法有效,但它会将许多查询发送到数据库,而我正在寻找一种方法来仅通过一个查询即可完成所有操作.根据 @Slauma 的指导(在上面的链接的答案中进行了解释),我将查询更改为以下内容:

Though this approach works, it sends many queries to the database and I am searching for a way to do this all in just one query. With @Slauma's guidance (explained in the answer at the above link), I have changed the query to this one:

var model2 = DbContext.SitePages
    .Where(p => p.ParentId == null && p.Level == 1)
    .OrderBy(p => p.Order)
    .Include(p => p.Children // Children: how to order theme???
        .Select(c => c.Children) // Grandchildren: how to order them???
    ).ToList();

现在,如何选择子代(如上面的第一个代码示例所示)?

Now, how can I order children (and grandchildren) when selecting them (such as shown in the first code example above)?

推荐答案

不幸的是,急切加载(Include)不支持对已加载的子集合进行任何筛选或排序.您可以通过三种选择来实现自己的目标:

Unfortunately eager loading (Include) doesn't support any filtering or sorting of loaded child collections. There are three options to achieve what you want:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆