有效地查询列表中的列表

时间:2012-12-09 21:19:11

标签: linq linq-to-sql

我正在尝试查询产品列表,每个产品都有一个订单列表。

这样的事情:

from s in products
join o in orders on s.ProductID = o.ProductID
select new ProductRecord
{
  ProductName = s.Name,
  OrderList = o.Select(x=>new OrderRecord(OrderID = x.OrderID, OrderName = x.OrderName).ToList()
}

OrderList是List<OrderRecord>

我的查询比这复杂得多,但这说明了这个想法。

最后,我想在我的网页上列出这样的内容:

Product 1
    Order 1
    Order 2
    Order 3

Product 2
    Order 4
    Order 5
    Order 6

但这并不是很好用。这是一个缓慢的查询,Mini Profiler说我的页面上有100个重复的查询。如果我拿出那些OrderList的东西,一切都很活泼。

我认为我正在接近这个问题。如何有效地查询?

1 个答案:

答案 0 :(得分:3)

从查询中删除ToList。还可以使用group join来获取产品订单:

var query = from s in context.Products
            join o in context.Orders on s.ProductID equals o.ProductID into g
            select new ProductRecord
            {
                  ProductName = s.Name,
                  OrderList = g.Select(x => new OrderRecord() 
                                            { 
                                                OrderID = x.OrderID, 
                                                OrderName = x.OrderName
                                            })
            };

OrderList应为IEnumerable<OrderRecord>。以下是SQL事件探查器向我显示的此类查询:

SELECT 
[Project1].[C1] AS [C1], 
[Project1].[Name] AS [Name], 
[Project1].[C2] AS [C2], 
[Project1].[OrderID] AS [OrderID]
FROM ( SELECT 
    [Extent1].[Name] AS [Name], 
    1 AS [C1], 
    [Extent2].[OrderID] AS [OrderID], 
    CASE WHEN ([Extent2].[OrderID] IS NULL) 
         THEN CAST(NULL AS int) ELSE 1 END AS [C2]
    FROM  [dbo].[Products] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Orders] AS [Extent2] 
         ON [Extent1].[ProductID] = [Extent2].[ProductID]
)  AS [Project1]
ORDER BY [Project1].[ProductID] ASC, [Project1].[C2] ASC