简体   繁体   English

使用LINQ联接多个字段

[英]Use LINQ to Join on Multiple Fields

How would I do this in LINQ? 我将如何在LINQ中做到这一点?

SQL

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

Here is my attempt. 这是我的尝试。 The problem seems to be with "assoc.AssociationType == "DS". Is it part of the join or the Where clause? 问题似乎出在“ 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 };

Thanks in advance 提前致谢

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

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

Yes, "and" should be "&&", but the answer to your question is that in Linq the predicate assoc.AssociationType == "DS is not part of the join. 是的,“和”应为“ &&”,但您的问题的答案是在Linq中谓词assoc.AssociationType == "DS不是assoc.AssociationType == "DS一部分。

In SQL you could make it part of a join statement 在SQL中,您可以使其成为连接语句的一部分

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

but in Linq statments you just add it as a predicate, the way you did (apart from the "and" issue). 但是在Linq陈述中,您只是将其添加为谓词即可(除了“ and”问题)。

In SQL, in terms of execution plan (performance), it does not matter whether you add it to the JOIN phrase or put it into a separate WHERE condition. 在SQL中,就执行计划(性能)而言,将其添加到JOIN短语中还是将其置于单独的WHERE条件中都没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM