2012-10-15 73 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();

相關問題