实体框架选择仅包含一个孩子的人

时间:2016-02-22 12:39:01

标签: c# .net entity-framework

假设我有一个包含子列表的Person类。

不是我想查询数据库以获取有孩子的人员列表:

return context.Person.Include(p => p.Children);

好了,现在我想修改那个查询,结果我得到了Person列表,但只有一个孩子(假设最老的一个按年龄desc排序)

有可能吗?

提前致谢

2 个答案:

答案 0 :(得分:2)

您所描述的内容可以通过以下查询来实现:

from p in Persons
from ch in p.Children.OrderByDescending(x => x.Age).Take(1)
select new { p,ch }

您可以使用Take(1)代替FirstOrDefault():结果集也会包含没有子女的人:

from p in Persons
select new { p, p.Children.OrderByDescending(x => x.Age).FirstOrDefault() }

然而,Children类的集合Person会自动维护为1 Children个实例的所有Person的集合,并且此含义无法更改。

据我所知,这是不可能的,你需要创建一个包含1个人+ 1个Child实例的新类。

答案 1 :(得分:0)

我为这样的一些案例创建了一个库。

https://github.com/deyunote/EntityFramework.Include

使用此库,您可以描述如下

context.Person.Include(p => p.Children,
                       p => p.Children.OrderByDescending(x => x.Age).Take(1).ToList())
              .ToListWithInclude(); //Async:ToListWithAsync()