Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在一次往返中从单个LinQ到SQL表达式返回多个结果?_Sql_Linq - Fatal编程技术网

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

如何在一次往返中从单个LinQ到SQL表达式返回多个结果?,sql,linq,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

我正在重写一段我继承的古老代码,我正在研究一个对大型表执行大规模联接的查询,然后对结果表执行一系列分组操作以提取数据:

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发送到DB服务器,数据在一次网络往返中作为n个单独的结果返回

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

除了尝试在结果集上强制执行distinct之外,我看不到在这里使用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接口使用它们。看