【问题标题】:complex linq-to-sql join with 4 tables: how many where clauses should there be?具有 4 个表的复杂 linq-to-sql 连接:应该有多少个 where 子句?
【发布时间】:2012-08-01 03:58:23
【问题描述】:

我正在编写一个连接 4 个表的 linq-to-sql 查询。我有这样的事情:

var MyQuery = from a in MyDC.Table1
              from b in MyDC.Table2
              from c in MyDC.Table3
              from d in MyDC.Table4
              where .....

我的问题是关于where 子句。我可以这样写 where 子句:

   where a.PropX == b.PropY && b.PropX == c.PropZ && ....

或多个这样的子句:

   where a.PropX == b.PropY
   where b.PropX == c.PropZ
   ...

选择一个或另一个选项会有什么不同吗?

感谢您的建议。

【问题讨论】:

标签: c# linq-to-sql


【解决方案1】:

以上两种我都不喜欢;相反,我会遵循 SQL 语法,它不会隐藏查询的意图:

var query  from a in MyDC.Table1 
           join b in MyDC.Table2 on a.Property1 equals b.Property2
           join c in MyDC.Table3 on b.Property1 equals c.Property5
           join d in MyDC.Table4 on c.Property2 equals d.Property1
select ...

【讨论】:

  • +1:内置语法时,为什么还要麻烦复杂的 where 子句?
【解决方案2】:

你不应该这样做。您的代码将生成所有数据源的笛卡尔连接(乘法),然后根据您的条件对其进行过滤。相反,您应该使用 Icarus 建议的简单连接。

(我知道您的困惑来自哪里:在某些 SQL 方言中,您可以在 WHEREJOIN 中编写连接条件。但 LINQ 不是这种情况。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多