【问题标题】:Use LINQ to Join on Multiple Fields使用 LINQ 连接多个字段
【发布时间】:2012-06-01 20:33:15
【问题描述】:

我将如何在 LINQ 中执行此操作?

SQL

Where tblAccounts.AccountCode = tblAccountAssociations.ChildCode
And tblAccountAssociations.AssociationType = "DS"

这是我的尝试。问题似乎出在“assoc.AssociationType == "DS"。它是联接的一部分还是 Where 子句的一部分?

var customers = 
    from customer in context.tblAccounts 
    join assoc in context.tblAccountAssociations on customer.AccountCode equals assoc.ChildCode 
    where customer.AccountType == "S" and assoc.AssociationType == "DS" 
    orderby customer.AccountType 
    select new { Customer = customer, Assoc = assoc };

提前致谢

【问题讨论】:

  • 您需要添加更多代码。您的 SQL 没有显示完整的查询,并且您的 LINQ 没有显示您正在查询的集合或类型。例如;什么是“关联”?
  • vcsjones - 我没有使用 tablea 中的 col1、col2 到 tableb 中的 col1、col2。我的条件之一是硬编码值,即“DS”
  • 你现在所拥有的东西不能用吗?看起来应该没问题。
  • CAbbott - 这不起作用。除其他外,它说“查询主体必须以 select 子句或 group 子句结尾。

标签: c# linq inner-join multiple-tables


【解决方案1】:

根据 MSDN (http://msdn.microsoft.com/en-us/library/bb311043.aspx),在“where”子句中使用“&&”而不是“and”来指定多个条件。

【讨论】:

    【解决方案2】:
    var customers =  
    from customer in context.tblAccounts  
    join assoc in context.tblAccountAssociations on customer.AccountCode equals assoc.ChildCode  
    where customer.AccountType == "S" **&&** assoc.AssociationType == "DS"  
    orderby customer.AccountType  
    select new { Customer = customer, Assoc = assoc }; 
    

    【讨论】:

      【解决方案3】:

      是的,“and”应该是“&&”,但您的问题的答案是在 Linq 中谓词 assoc.AssociationType == "DS 不是连接的一部分。

      在 SQL 中,您可以将其作为连接语句的一部分

      ...
      FROM tblAccounts c
      INNER JOIN tblAccountAssociations a ON
          c.AccountCode = a.ChildCode AND a.AssociationType == "DS" 
      ...
      

      但在 Linq 语句中,您只需将其添加为谓词,就像您所做的那样(除了“和”问题)。

      在 SQL 中,在执行计划(性能)方面,无论是添加到 JOIN 短语中,还是放入单独的 WHERE 条件中。

      【讨论】:

        猜你喜欢
        • 2011-04-29
        • 1970-01-01
        • 2018-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多