【问题标题】:LINQ to Entiites, left outer join of a group byLINQ to Entities,组的左外连接
【发布时间】:2019-12-05 08:46:55
【问题描述】:

我可以轻松构建执行以下操作的 SQL 查询。

对于“Table1”的每一行,我想要计算“Status”不等于 5 的相关“Table2”记录的数量。可能没有匹配项,所以我使用“左外连接”,然后在其中使用“分组依据”来查找匹配的总数。

以下查询用作 SQL。它要么输出 null 值,因为根本没有匹配项,要么输出一个实际的整数计数,如果至少有一个匹配项。

select
    Table1.Id,
    Table2Outer.Count
from
    Table1
    left outer join
    (
        select
            Table2.Id,
            COUNT(*) as Count
        from
            Table2
        where
            Table2.Status != 5
        group by
            Table2.Id
    ) as Table2Outer on Table2Outer.Id = Table.Id

不幸的是,我无法弄清楚如何将其转换为 LINQ to Entities。以下甚至没有编译,我被卡住了!

var x = (from t1 in ctx.Table1
         join t2 in ctx.Table2 on { t1.Id, t2.Status } equals new { t2.Id, Status != 5 } into t2Outer
         from t2OuterB in t2Outer.DefaultIfEmpty()
         group t2Outer by ?);

有什么想法吗?

【问题讨论】:

  • 您在Table1 上是否有指向Table2 的导航属性?如果是这样,这将变得容易得多。
  • 是的,Table1 实体有一个名为 Table2s 的导航,其类型为 HashSet
  • 嗯,多看代码。那 Table2s 不是可导航的属性。所以看起来我不能使用你已经做出的好答案。对不起。
  • 还有其他想法吗?
  • 如果您将 SQL 重写为 SELECT Table1.Id, (SELECT COUNT(*) FROM Table2 WHERE Table2.Id = Table1.Id AND Table2.Status <> 5) AS [Count] FROM Table1 ... 它会产生与原始查询相同的结果吗?看起来外部连接对于您正在尝试做的事情来说有点矫枉过正。

标签: c# linq linq-to-entities


【解决方案1】:

使用子查询计算投影中的子记录。

var x = from t1 in ctx.Table1
        select new
        {
            t1.Id,
            Count = (from t2 in ctx.Table2
                     where t2.Status != 5
                     where t2.Id == t1.Id
                     select t2).Count()
        };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多