2012-10-15 75 views
0

我正在写一个这样的查询:使用内部集合查询另一个子查询

var TheQuery = (from t in MyDC.Table1 
       where .... 
       select new SomeContainerModel() 
       { 
        Collection1 = (from t2 in MyDC.Table2 
            .... 
            select new SomeModel() 
            { 
             SomeID = t2.SomeID 
            } 

        Collection2 = (from x in Collection1 
            from t3 in MyDC.Table3 
            where x.SomeID == t3.SomeOtherID 

我想要做的,是使用Collection1结果作为Collection2输入。

这可能吗?

回答

2

您可以使用let关键字来为子查询结果引入新的范围变量。

var theQuery = (from t in MyDC.Table1 
       let subQuery = (from t2 in MyDC.Table2 
           ... 
           select new SomeModel() { SomeID = t2.SomeID }) 
       where ....     
       select new SomeContainerModel() 
       { 
        Collection1 = subQuery, 
        Collection2 = (from x in subQuery 
            from t3 in MyDC.Table3 
            where x.SomeID == t3.SomeOtherID) 
       }; 
+0

好的,谢谢你的回答! – frenchie

0

问题是Collection1与Collection2不兼容。您将Collection1转换为模型,不能再转换为SQL。

我建议您将您的查询视为IQuerable。只有当您需要物理执行并检索数据时,才会到最后。

试想每个查询与Transact-SQL脚本,甚至当你与MyDC.Table3加入它,你真的才刚刚添加的子查询,喜欢的东西:

SELECT * 
FROM Table3 a, 
FROM (SELECT * FROM Table2 WHERE....) as SubQuery 
WHERE a.SomeID == SubQuery.SomeOtherID 

所以,尽量使用匿名类型,而不是SomeModel();

相关问题