EF Code First - 如何使用包含扩展方法过滤相关 objects

EF Code First -how to filter related objects using Include extension method

给定一个 EF-Code 第一个 CTP5 实体布局,例如:

public class Person 
{
     public List<Children> Childrens { get; set; }
}

public class Children
{
    public int Age { get; set; }
}

我想做:

PersonQuery.Include(x => x.Childrens.OrderByDescending(child => child.Age).Take(3))

并且只从列表中得到 3 个年龄较大的孩子。

例如:

我有 5 个孩子,年龄分别为 5、10、15、20、25 岁

我想要 select 这个人 + 3 名年龄分别为 25、20、15 岁的孩子的名单。

这是我的错误:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

您不能在 Include 扩展方法中进行查询来过滤相关对象,您必须仅指定一个导航 属性 或一个表达式来组成额外的包含。看看这个 link(备注部分),了解如何使用它。

您可以在使用 Select 方法投影查询时过滤相关对象:

var query=PersonQuery.Include(x => x.Children)
                     .Select(p=>new {PersonName=p.Name,
                                     Children=p.Children.OrderByDescending(child => child.Age).Take(3)});

如果您想了解更多有关如何将 Linq 投射到实体查询的信息,那么您应该看到这个 post