【问题标题】:LINQ JOIN with a CASE condition in JOIN parameters在 JOIN 参数中带有 CASE 条件的 LINQ JOIN
【发布时间】:2020-04-14 05:28:03
【问题描述】:

我有一个运行良好的相对简单的 SQL 查询,但不知道如何将其转换为 LINQ。诀窍是 JOIN 中的 CASE 语句,并且 CASE 引用两个表。这是SQL

SELECT *
FROM table1 t1
INNER JOIN table2 t2 ON
    t2.col1 = t1.col1
AND t2.col2 = CASE
                  WHEN t2.col3 = 1 THEN t1.col2
                  ELSE t1.col3 END

如您所见,如果我在 t2.col3 中的 bool 为真,我将在 t1.col2 上加入 t2.col2。如果布尔为假,我在 t1.col3 上加入 t2.col2。在 SQL 中,我得到了想要的结果。在 LINQ 中我遇到了两个问题:首先,我似乎无法在连接 (CASE) 中使用三元组,其次,我无法让 LINQ 连接来引用连接对象中的两个表。

在 LINQ 中是否有干净的方法或任何方法来完成此 SQL 查询?

编辑

我尝试过的一些 LINQ:

var result = from t1 in table1
             join t2 in table2
             on new { t1.col1, t2.col3 ? t1.col2 : t1.col3} equals
                new { t2.col2, t2.col2}

在这种情况下,错误发生在三元运算的第 3 行并显示为t2 is not in scope on the left side of 'equals'

【问题讨论】:

  • 你试过什么 LINQ 代码?
  • 在问题中添加。
  • 在 WHERE 子句中使用 AND/OR 而不是 case 表达式通常更好。
  • 我不知道在这种情况下会是什么样子。你能详细说明一下吗?
  • 唯一的错误是{ t1.col1, t2.col3 ? t1.col2 : t1.col3} 不是有效的匿名类型声明。它甚至不应该编译。如果您收到报告的错误,则意味着您没有显示实际代码,这永远不会有帮助。

标签: c# sql linq


【解决方案1】:

LINQ 只直接支持equijoins。如果你想做任何其他类型的连接,你需要一个交叉连接和where

from t1 in table1
from t2 in table2
where t1.col1 == t2.col1 && ((t2.col3 = 1 && t2.col2 = t1.col2) || (t2.col3 != 1 && t2.col2 = t1.col3))
select ..

【讨论】:

    【解决方案2】:

    对于这种情况,我们需要使用where子句。

     var result = from t1 in table1
                  join t2 in table2 on t1.col1 equals t2.col1
                  where t2.col2 == (t2.col3 == "1" ? t1.col2 : t1.col3)
                  select t2.col2;
    

    或者

    var result2 = from t1 in table1
                  from t2 in table2.Where(x=>x.col2 == (x.col3 == "1" ? t1.col2 : t1.col3) &&  x.col1 == t1.col1)
                  select t2.col2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-24
      • 2016-01-11
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      相关资源
      最近更新 更多