【问题标题】:SQL to LINQ - Left Join two conditionsSQL to LINQ - 左连接两个条件
【发布时间】:2018-07-13 00:21:51
【问题描述】:

如何将此外部左连接转换为 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 子句是在 join 之后应用的。

【问题讨论】:

  • LEFT OUTER JOIN in LINQ的可能重复
  • 对于这样的多个参数,您必须创建匿名类型,并将值作为比较 on new {t1.Code, id ="xxxxx"} equals new {t2.Code, t2.id} 的键。
  • 仍然无法正常工作,因为 sub.id 只在一张桌子上....

标签: c# linq


【解决方案1】:
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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 2011-10-14
    相关资源
    最近更新 更多