使用LINQ加入多个字段

时间:2012-06-01 20:33:16

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

我如何在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 };

提前致谢

3 个答案:

答案 0 :(得分:0)

根据MSDN(http://msdn.microsoft.com/en-us/library/bb311043.aspx),您使用“&&”而非“和”来指定“where”中的多个条件“条款。

答案 1 :(得分:0)

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 }; 

答案 2 :(得分:0)

是的,“和”应为“&&”,但您的问题的答案是,在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条件中都无关紧要。