Enormous SQL generated for Linq-to-Sql Grouping
I have one Linq to SQL query that simply joins three tables and then performs grouping. Here is the query:
(from s in mktActualSales
join p in sysPeriods on s.PeriodID equals p.PeriodID
join d in setupDesignations on s.PositionID equals d.DesignationID
group new { s, p } by new{d.Title,d.DesignationID} into temping
select
new
{
SPOPosition = temping.Key.Title,
SalesPeriods = temping.Select(x=>new {PeriodID = x.p.PeriodID, StartDate = x.p.StartDate, EndDate = x.p.EndDate, SaleTargetID = x.s.ActualSaleID, IsApproved = x.s.IsApproved}),
PositionID = temping.Key.DesignationID
开发者_开发百科 }).Take(5)
When I inspect SQL generated (executed) by this query in LinqPad, there are 6 SQL statements; first one performs join and grouping and rest of queries are the same just calling same query over and over again with different parameters. Obviously parameters are the values included in Key of the group.
It makes me believe that for a record with 130 groups Linq will hit the database 131 times. How can I save so much hits to the database? Should I perform grouping after loading data into memory i.e after calling ToList on joined query?
(I am assuming mktActualSales is your table and you missed putting the Datacontext in the question.)
If it is your table you should have a look at LoadOptions on your DataContext. With this you can eager load some of the related data and this might prevent the repetitive queries.
http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx
If it is not a table, have a look on how you populate mktActualSales but judging from your question I assume it is a table.
精彩评论