LInq在on子句中保留了多个条件的连接

时间:2016-04-28 08:07:13

标签: c# entity-framework linq linq-to-sql

我有一个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中编写此语句?

1 个答案:

答案 0 :(得分:4)

  • 如果你真的想用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 }