不支持嵌套查询:实体框架在分组的左连接

时间:2016-08-03 12:23:59

标签: entity-framework linq-to-entities entity-framework-6

考虑这个问题:

from e in db.MyEntities

join o in db.MyOtherEntities
on new e.Foo equals o.Foo into others
from o in others.DefaultIfEmpty()

select new
{
  Value1 = e.Value1,
  Value2 = o.Value2
};

通过这种简单的左连接,实体框架无法执行以下组

from e in query group e by new { } into g select g.Count()

这可能看起来很模糊,但对于自动网格实现而言,查询实际上是常见的事情。

我使用DevExtreme的数据库遇到过这种情况:总摘要不适用于左连接的查询。

你得到的是

NotSupportedException: The nested query is not supported. Operation1='GroupBy' Operation2='MultiStreamNest'

但这有效:

from e in query.Take(1) select { Count = query.Count(), /* other aggregates */ }

这样做:

from e in query group e by e.SomePropertyThatsActuallyConstant into g select g.Count()

1 个答案:

答案 0 :(得分:1)

有一种解决方法。您可以这样编写查询:

from e in db.MyEntities

from o in db.MyOtherEntities.Where(o => o.Foo == e.Foo).DefaultIfEmpty()

select new
{
  Value1 = e.Value1,
  Value2 = o.Value2
};

奇怪的是,当你在join之后放一个where子句时它也有效:

from e in db.MyEntities

join o in db.MyOtherEntities
on new e.Foo equals o.Foo into others
from o in others.DefaultIfEmpty()

where e.Value1 == e.Value1

select new
{
  Value1 = e.Value1,
  Value2 = o.Value2
};

where子句条件不能只是常量,我想EF足够聪明,否则就会减少它。