包含带有聚合数据的附加列的EF查询

时间:2012-01-04 21:21:35

标签: linq entity-framework entity-framework-4

我有一张表OrderDetail:

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 = ?? }

谢谢, 罗杰马丁

1 个答案:

答案 0 :(得分: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]}