2012-01-04 109 views
1

我有一個表的OrderDetail這樣附加柱:EF查詢包括與聚合數據

ID OrderNumber LineItem Qty 
--------------------------- 
1 10000   1  2 
2 10000   2  5 
3 10000   3  1 
4 10001   1  10 

我想與包含每個順序(上ORDERNUMBER分組)的最大數量的額外的列返回此表,像這樣:

ID OrderNumber LineItem Qty MaxQty 
----------------------------------- 
1 10000   1  2  5 
2 10000   2  5  5 
3 10000   3  1  5 
4 10001   1  10 10 

我一直在努力如何把EF語法放在一起。我想象的結果將是某種匿名類型,將OrderDetail記錄作爲第一個屬性,將數量作爲第二個屬性,如select new { OrderDetail = ??, MaxQty = ?? }

感謝, 羅傑·馬丁

回答

2

你可以得到MaxQty用一個子查詢。使用EF DBContext API:

public class MyContext : DbContext 
{ 
    public DbSet<OrderDetail> OrderDetails { get; set; } 
} 

var context = new MyContext(); 
var result = context.OrderDetails.Select(od => 
    new { 
      OrderDetail = od, 
      MaxQty = context.OrderDetails 
      .Where(o => o.OrderNumber == od.OrderNumber).Max(a => a.Qty) }); 

它會生成以下SQL查詢:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[OrderNumber] AS [OrderNumber], 
[Extent1].[LineItem] AS [LineItem], 
[Extent1].[Qty] AS [Qty], 
(SELECT 
    MAX([Extent2].[Qty]) AS [A1] 
    FROM [dbo].[OrderDetails] AS [Extent2] 
    WHERE [Extent2].[OrderNumber] = [Extent1].[OrderNumber]) AS [C1] 
FROM [dbo].[OrderDetails] AS [Extent1]} 
+0

謝謝 - 答案是很簡單,但我仍然環繞我的頭周圍EF。真的很感激它... – Roger 2012-01-04 22:58:11