2011-08-30 26 views
0

我正在重寫一段古代代碼,我繼承了這個代碼,我正在查看一個在大型表上執行大量連接的查詢,然後在結果表上執行一系列分組操作來「提取」數據:如何在一次往返中將單個LinQ to SQL表達式的多個結果返回?

INSERT INTO #teh_temp_table 
SELECT * FROM teh_large_table 
INNER JOIN teh_other_large_table 

SELECT customer_id, customer_name FROM * #teh_temp_table 
GROUP BY customer_id, customer_name 
ORDER BY customer_name 

SELECT city_id, city_name FROM * #teh_temp_table 
GROUP BY city_id, city_name 
ORDER BY city_name 

-- repeated n-2 times ... 

這個大SQL語句發送到數據庫服務器用ADO.NET SqlCommand和數據返回作爲一個網絡往返ň獨立的結果。

我很難將此轉換爲LinQ to SQL。我一直在試圖做類似於:

from tlt in teh_large_table 
join tolt in teh_other_large_table on tlt.pkey equals tolt.fkey into teh_temp_table 

from tmp in teh_temp_Table 
group tmp by new { tmp.customer_id, tmp.customer_name } into customers 

from tmp in teh_temp_table 
group tmp by new { tmp.city_id, tmp.city_name } into cities 

select new { customers, cities } 

但編譯器抱怨。有沒有辦法發出一個等價的LinQ查詢,它不僅可以檢索數據,而且還可以在單​​次網絡往返中返回它?正如你可以想象的那樣,我不想多次執行那個令人討厭的連接。

回答

0

除了試圖在結果集上強制區分外,我沒有看到在這裏使用Group操作的優勢。由於LINQ to SQL無法從LINQ返回多個結果,因此可以將它們推送到臨時表中,然後根據某種類型對結果進行分組。願意爲你下面的工作:

var bigTable = from large in teh_large_table 
       from other in teh_other_large_table 
       select new { ??? }; // TODO: Supply needed columns here 

var kvPairs = from customer in bigTable 
       select new {Id = customer.Customer_id, Name = customer.Customer_name, Type="Customer"} 
       .Union(
       from city in teh_temp_table 
       select new {Id = city.City_id, Name = city.City_name, Type="City"} 
      ).Distinct(); 

var groupedKvPairs = from pair in kvPairs 
        group pair by pair.Type into grouped 
        select new {pairType = key, 
           vals = from row in grouped 
             orderby row.Name 
             select new { row.Id, row.Name}}; 

作爲替代方案,你也可以建立一個存儲過程返回多個結果,然後使用IMultipleResults接口來使用它們。見http://www.thinqlinq.com/Default/Using-LINQ-to-SQL-to-return-Multiple-Results.aspx