I'm rewriting an ancient piece of code that I've inherited and I'm looking at a query that performs a massive join on large tables, and then does a series of grouping actions on the resulting table to "distill out" data:
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 ...
This large SQL statement is sent to the DB server with a ADO.NET SqlCommand, and the data is returned as n separate results in one network round trip.
I'm having difficulties translating this to LinQ to SQL. I've been attempting to do something similar to:
开发者_如何转开发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 }
but the compiler complains. Is there a way to issue an equivalent LinQ query that not only retrieves the data but also returns it, in a single network round-trip? As you can imagine, I don't want to perform that big nasty join more than once.
Other than trying to force distinct on the result sets, I'm not seeing the advantage of using the Group operation here. Since LINQ to SQL can't return multiple results from LINQ, you could push them into a your temp table and then group the results based on some type. Would the following work for you:
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}};
As an alternative, you could also set up a Stored Proc returning multiple results and then use the IMultipleResults interface to consume them. See http://www.thinqlinq.com/Default/Using-LINQ-to-SQL-to-return-Multiple-Results.aspx
精彩评论