简体   繁体   中英

Use LINQ to Join on Multiple Fields

How would I do this in 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?

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.

In SQL you could make it part of a join statement

...
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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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