需要帮助将嵌套的SQL语句转换为LINQ

时间:2009-04-30 21:03:54

标签: c# sql linq linq-to-sql

我有类似的声明,我需要在Linq中运行。我开始使用.Contains,并且可以让第一层工作,但似乎无法掌握我需要做什么来获得额外的层。

这是SQL语句:

select * 
from aTable
where aTableId in
    (select aTableId from bTable
    where bTableId in 
        (select bTableId from cTable
        where cTableId in
            (select cTableId from dTable
            where dField = 'a guid'
            )
        )
    )

1 个答案:

答案 0 :(得分:3)

嗯,最简单的翻译是:

var query = from a in aTable
            where (from b in bTable
                   where (from c in cTable
                          where (from d in dTable
                                 where dField == "a guid"
                                 select d.cTableId)
                                .Contains(c.cTableId)
                          select c.bTableId)
                         .Contains(b.bTableId)
                   select b.aTableId)
                   .Contains(a.aTableId)
            select a;

但是,联接可能会更简单:

var query = from a in aTable
            join b in bTable on a.aTableId equals b.aTableId
            join c in cTable on b.bTableId equals c.bTableId
            join d in dTable on c.cTableId equals d.cTableId
            where d.dField == "a guid"
            select a;

我没有检查,但我认为他们会做同样的事情......