如何在一次往返中从单个LinQ to SQL表达式返回多个结果?

时间:2011-08-30 15:24:20

标签: sql linq

我正在重写我继承的一段古老代码,我正在查看一个在大型表上执行大量连接的查询,然后对生成的表执行一系列分组操作以“提取” “数据:

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 ...

使用ADO.NET SqlCommand将此大型SQL语句发送到数据库服务器,并在一次网络往返中将数据作为 n 单独返回结果返回。

我在将此转换为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查询,不仅可以检索数据,还可以在单​​个网络往返中返回它?你可以想象,我不想不止一次地执行那个大讨厌的连接。

1 个答案:

答案 0 :(得分: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