查询使用实体框架6.实体框架生成嵌套集合
假设我有两个嵌套集合ICollection<Child>
和ICollection<Child2>
实体Parent
。我想预先抓取两种:
dbContext.Parent.Include(p => p.Child).Include(p => Child2).ToList()
这会产生一个很大的查询,它看起来像这样在较高的水平:
SELECT ... FROM (
SELECT (parent columns), (child columns), NULL as (child2 columns)
FROM Parent left join Child on ...
WHERE (filter on Parent)
UNION ALL
SELECT (parent columns), NULL as (child columns), (child2 columns)
FROM Parent left join Child2 on ...
WHERE (filter on Parent)
))
有没有办法让实体框架的行为类似于批在NHibernate(或JPA,EclipseLink,Hibernate等)中获取,你可以指定你想先查询父表,然后分别为每个子表查询?
SELECT ... from Parent -- as usual
SELECT ... from Child where parent_id in (list of IDs)
SELECT ... from Child2 where parent_id in (list of IDs)
-- alternatively, you can specify EXISTS instead of IN LIST:
SELECT ... from Child where exists (select 1 from Parent where child.parent_id = parent.id and (where clause for parent))
我觉得这更容易理解和推理,因为它更类似于你手动编写的SQL。此外,它还可以防止结果集中多余的父表行。另一方面,这是更多的往返旅行。