繁体   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