Linq to SQL:左联接分组集可进行交叉应用/外部应用

Mas*_*ity 5 group-by left-join linq-to-sql c#-4.0

基本上,我是在进行报表类型查询,在这里我要汇总多个表中的数据,然后将其连接到单个表中。

它看起来像这样:

var docs = from x in DB.Docs
           group x by x.PersonId into g
           select new { 
                g.Key, 
                totalSent = g.Sum(x => x.SentDate.HasValue ? 1 : 0),
                lastSent = g.Max(x => x.SentDate)
                ...
           };

var summary = from x in DB.People
              from y in docs.Where(y => y.Key == x.Id).DefaultIfEmpty()
              select new {
                   x.Id,
                   x.Name,
                   y.totalSent,
                   y.lastSent
              }
Run Code Online (Sandbox Code Playgroud)

我希望这个创建的sql可以加入DB.People的结果,docs但是我却得到了一些疯狂的CROSS APPLY(( SELECT NULL AS [EMPTY]) as [t1] OUTER APPLY ...东西。

我已经尝试过可以想到的左联接语法的每个变体,甚至包裹docs在另一个查询中,而且得到的结果相同。

我想念什么?

Amy*_*y B 0

from x in DB.People
from y in docs.Where(y => y.Key == x.Id).DefaultIfEmpty() 
Run Code Online (Sandbox Code Playgroud)

上面将清楚地生成笛卡尔结果,稍后对其进行过滤。

也许您想加入:

from x in DB.People
join y2 in docs on x.Id equals y2.Key into g
from y in g.DefaultIfEmpty() 
Run Code Online (Sandbox Code Playgroud)

这个怎么样:

from x in DB.People
let g = x.Docs
select new
{
  x.Id,
  x.Name,
  totalSent = g.Sum(y => y.SentDate.HasValue ? 1 : 0),
  lastSent = g.Max(y => y.SentDate)
}
Run Code Online (Sandbox Code Playgroud)