首页 > 解决方案 > SQL to LINQ - 左连接两个条件

问题描述

如何将此外部左连接转换为 LINQ?

    SELECT *  from table1 t1
      left join table2 t2 on  t1.code = t2.code AND  t2.id ='xxxxx'
       WHERE t1.someId = 2

我正在尝试这样的事情:

from t1 in db.table1
join t2 in db.table2 on t1.Code equals t2.Code
into oj
from sub in oj.DefaultIfEmpty()
where t1.someId == 2
where (sub.id == 'xxxx')

但并非左表中的所有行都被返回。我认为 where 子句在加入后应用。

标签: c#linq

解决方案


var res=(from t1 in table1.Where(x=>x.someId==2)
         join t2 in table2.Where(y=>y.id==xxxx)
         on t1.code = t2.code
         into r 
         from t3 in r.DefaultIfEmpty()
         select new {t1,t3}).ToList();

推荐阅读