LInq left join with multiple condition in on 子句
LInq left join with multiple condition in on clause
我在 SQL 中有一个连接,我需要在 linq 中编写它,这里是 select
语句:
select * from products p
left join customer cust
on((cust.identifier = p.orgID or cust.identifier = p.personalno) and cust.identifier is not null);
如何在 linq 中编写此语句?
如果你真的想用JOIN
来做,你可以这样做:
from cust in customer
join _p1 in products on cust.identifier equals _p1.orgID into _p1
from p1 in _p1.DefaultIfEmpty()
join _p2 in products on cust.identifier equals _p2.personalno into _p2
from p2 in _p2.DefaultIfEmpty()
where cust.identifier != null
&& (p1 != null || p2 != null)
select new { Customer = cust, Product = p1 == null ? p2 : p1 }
没有 JOIN
关键字的更简单的解决方案是:
from p in products
from cust.Where(q => q.identifier != null && (p.orgID == q.identifier || p.personalno == q.identifier)).DefaultIfEmpty()
where cust != null
select new { Product = p, Customer = cust }
要回答标题建议的问题,请执行以下操作以在多个条件下进行连接,但请注意,这仅适用于 AND
条件而不适用于 OR
条件:
from t1 in Table1
join t2 in Table2 on new { Criteria1 = t1.criteria1, Criteria2 = t1.criteria2 } equals new { Criteria1 = t2.criteria1, Criteria2 = t2.criteria2 }
select new { T1 = t1, T2 = t2 }
我在 SQL 中有一个连接,我需要在 linq 中编写它,这里是 select
语句:
select * from products p
left join customer cust
on((cust.identifier = p.orgID or cust.identifier = p.personalno) and cust.identifier is not null);
如何在 linq 中编写此语句?
如果你真的想用
JOIN
来做,你可以这样做:from cust in customer join _p1 in products on cust.identifier equals _p1.orgID into _p1 from p1 in _p1.DefaultIfEmpty() join _p2 in products on cust.identifier equals _p2.personalno into _p2 from p2 in _p2.DefaultIfEmpty() where cust.identifier != null && (p1 != null || p2 != null) select new { Customer = cust, Product = p1 == null ? p2 : p1 }
没有
JOIN
关键字的更简单的解决方案是:from p in products from cust.Where(q => q.identifier != null && (p.orgID == q.identifier || p.personalno == q.identifier)).DefaultIfEmpty() where cust != null select new { Product = p, Customer = cust }
要回答标题建议的问题,请执行以下操作以在多个条件下进行连接,但请注意,这仅适用于
AND
条件而不适用于OR
条件:from t1 in Table1 join t2 in Table2 on new { Criteria1 = t1.criteria1, Criteria2 = t1.criteria2 } equals new { Criteria1 = t2.criteria1, Criteria2 = t2.criteria2 } select new { T1 = t1, T2 = t2 }