簡體   English   中英

使用LINQ聯接多個字段

[英]Use LINQ to Join on Multiple Fields

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

提前致謝

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

是的,“和”應為“ &&”,但您的問題的答案是在Linq中謂詞assoc.AssociationType == "DS不是assoc.AssociationType == "DS一部分。

在SQL中,您可以使其成為連接語句的一部分

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

但是在Linq陳述中,您只是將其添加為謂詞即可(除了“ and”問題)。

在SQL中,就執行計划(性能)而言,將其添加到JOIN短語中還是將其置於單獨的WHERE條件中都沒有關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM