如何为涉及自连接的多个连接编写LINQ? [英] How to write LINQ for multiple joins involving self join?
本文介绍了如何为涉及自连接的多个连接编写LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过自我联接将以下查询转换为LINQ表达式.
I am trying to translate the following query with self join to a LINQ expression.
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查询?
How can I correct the following LINQ query to match the correct SQL query above?
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();
推荐答案
如果您的incomingType
是固定的,为什么不简单使用Where
子句呢?
Why don't you simple use a Where
clause if your incomingType
is fixed?
还有多种联接条件的语法,如下所示: LINQ在C#中联接多个条件
Also there is syntax for multiple join conditions, as shown here: LINQ Joining in C# with multiple conditions
例如:
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
表中获取其值,则只需在连接条件中添加第三个参数即可,例如
If your incomingType
is not actually fixed, and it gets its value from the depends
table, you can just add a third parameter to the join condition, 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, type = r.someType1 }
equals
new { ID = d.ID, desc = d.DESC, type = d.someType2 }
where r.ID == incomingId
select r).AsEnumerable();
这篇关于如何为涉及自连接的多个连接编写LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文