如何编写涉及自联接的多个连接的LINQ?

时间:2016-09-19 07:06:25

标签: c# linq

我正在尝试将以下查询与自联接转换为LINQ表达式。

select r2.* from depends d
  join request r on d.DESC =r.DESC
  join request r2 on d.ID=r2.ID
  and d.TYPE ='sometype'
where r.ID= 12345

如何更正以下LINQ查询以匹配上面的正确SQL查询?

var result = (from d in depends
            join r in request on d.DESC equals r.DESC
            join r2 in request on d.ID == r2.ID && d.TYPE == incomingType.ToString()
            where r.ID == incomingId
            select r2).AsEnumerable();

1 个答案:

答案 0 :(得分:1)

如果Where已修复,为什么不简单地使用incomingType条款?

还有多个连接条件的语法,如下所示:LINQ Joining in C# with multiple conditions

E.g:

var result = (from d in depends
              where d.TYPE == incomingType.ToString()
              join r in request on
              new { ID = r.ID, desc = r.DESC }
              equals 
              new { ID = d.ID, desc = d.DESC }
              where r.ID == incomingId
              select r).AsEnumerable();

如果您的incomingType实际上没有修复,并且它从depends表中获取了它的值,您只需在连接条件中添加第三个参数,例如

var result = (from d in depends
              where d.TYPE == incomingType.ToString()
              join r in request on
              new { ID = r.ID, desc = r.DESC, type = r.someType1 }
              equals 
              new { ID = d.ID, desc = d.DESC, type = d.someType2 }
              where r.ID == incomingId
              select r).AsEnumerable();