[英]how can i write sql query with join and where clause in linq or lambda
I wrote below query in MsSQL
now I want to write this query using C# linq
我现在在
MsSQL
写了以下查询,现在我想使用C# linq
编写此查询
SELECT JD.*
FROM Job_Details JD
INNER JOIN MstCustomer Cust ON JD.Cust_ID = Cust.Cust_ID
WHERE Cust.SAP = 'Yes'
A fairly simple join
would do. 一个相当简单的
join
就可以了。
from jd in Job_Details
join cust in MstCustomer
on jd.Cust_ID equals cust.Cust_ID
where cust.SAP == 'Yes'
select jd
You asked for it using a lambda expression 您使用lambda表达式要求它
You only want the Customers with Cust.SAP equal to "Yes", but you don't want the SAP in the end result. 您只希望Cust.SAP的客户等于“是”,但不希望SAP最终结果。 Hence it is more efficient to join only with the customers you actually want in your final result.
因此,仅在最终结果中仅与您真正想要的客户一起加入会更有效率。 Therefore do the
Where
before the Join
: 因此做
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
})
TODO: if desired, make it one big LINQ statement. 待办事项:如果需要,可以使它成为一个大的LINQ语句。 Note that this doesn't influence the performance very much, as these statements do not perform the query.
请注意,这不会对性能产生太大影响,因为这些语句不会执行查询。 They only change the
Expression
of the query. 它们仅更改查询的
Expression
。 Only items that do not return IQueryable
perform the query: ToList / FirstOrDefault / Any / Max / ... 只有不返回
IQueryable
项目才执行查询:ToList / FirstOrDefault / Any / Max / ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.