簡體   English   中英

我如何在linq或lambda中使用join和where子句編寫sql查詢

[英]how can i write sql query with join and where clause in linq or lambda

我現在在MsSQL寫了以下查詢,現在我想使用C# linq編寫此查詢

SELECT JD.*
FROM Job_Details JD
INNER JOIN MstCustomer Cust ON JD.Cust_ID = Cust.Cust_ID
WHERE Cust.SAP = 'Yes'

一個相當簡單的join就可以了。

from jd in Job_Details 
join cust in MstCustomer
on jd.Cust_ID equals cust.Cust_ID
where cust.SAP == 'Yes'
select jd

您使用lambda表達式要求它

您只希望Cust.SAP的客戶等於“是”,但不希望SAP最終結果。 因此,僅在最終結果中僅與您真正想要的客戶一起加入會更有效率。 因此做Where之前Join

IQueryable<JobDetail> jobDetails = ...
IQueryable<Customer> mstCustomers = ...

// Step 1: filter only the Yes customers:
var yesCustomers = mstCustomers.Where(customer => customer.SAP == "Yes");

// Step 2: Perform the join and select the properties you want:
var result = jobDetails.Join(yesCustomers, // Join jobDetails and yesCustomers
   jobDetail => jobDetail.Cust_Id,         // from every jobDetail take the Cust_Id
   customer = customer.Cust_Id,            // from every customer take the Cust_Id
   (jobDetail, customer) => new            // when they match use the matching items
   {                                       // to create a new object
       // select only the properties
       // from jobDetail and customer
       // you really plan to use
   })

待辦事項:如果需要,可以使它成為一個大的LINQ語句。 請注意,這不會對性能產生太大影響,因為這些語句不會執行查詢。 它們僅更改查詢的Expression 只有不返回IQueryable項目才執行查詢:ToList / FirstOrDefault / Any / Max / ...

暫無
暫無

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

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