0

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

所以是这样的:

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东西拿出来,一切都会变得活泼。

我想我在处理这个问题时都错了。我如何有效地查询这个?

4

1 回答 1

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 Profiler 针对此类查询向我显示的内容:

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
于 2012-12-09T21:22:47.163 回答