LInq 左连接在 on 子句中有多个条件

R01*_*R01 3 c# linq entity-framework 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);
Run Code Online (Sandbox Code Playgroud)

如何在 linq 中编写此语句?

sch*_*nzo 8

  • 如果你真的想用 aJOIN来做,你可以这样做:

    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 }
    
    Run Code Online (Sandbox Code Playgroud)
  • 没有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 }
    
    Run Code Online (Sandbox Code Playgroud)
  • 要回答标题建议的问题,请执行以下操作以在多个条件上进行连接,但请注意,这仅适用于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 }
    
    Run Code Online (Sandbox Code Playgroud)