从SQL GROUP BY语句

时间:2017-01-29 00:12:56

标签: c# asp.net vb.net entity-framework linq

我正在使用Entity Framework在VB.NET和ASP.NET中编写发票系统来存储我的对象。我想总结任何特定月份的所有可计费行项目,并将它们整理成发票。以下SQL查询实现了这一点,但是我无法在Entity Framework代码中首先使用它:

SQL查询:

SELECT DISTINCT 
    [database].[dbo].[WorkOrderDetails].PriceCodeID,
    [database].[dbo].[WorkOrderDetails].[Description],
    SUM([database].[dbo].[WorkOrderDetails].[Quantity]) AS [Quantity],
    SUM([Subtotal]) AS Subtotal,
    SUM([Total]) AS Total
FROM 
    [database].[dbo].[WorkOrderDetails] 
INNER JOIN 
    [database].[dbo].[WorkOrders] ON [database].[dbo].[WorkOrderDetails].[WorkOrderID] = [database].[dbo].[WorkOrders].[WorkOrderID]
WHERE 
    [ClientID] = 182 
    AND [WorkOrders].[Date] >= '10/1/2016' 
    AND [WorkOrders].[Date] < '10/31/2016' 
GROUP BY 
    [PriceCodeID], [Description]

此查询的输出类似于以下内容:

PriceCodeID | Description | Quantity | Subtotal | Total  
------------+-------------+----------+----------+--------
26            BOX REFILE        19         47.50    47.50
28            BOX RETRIEVAL     15         37.50    37.50
98            Del/Pu Out       376        545.20   545.20
95            Shredding      16893        760.19   760.19

我的目标是:

  • WorkOrder:WorkOrderID,日期,ClientID (外键),列表(WorkOrderDetail

  • WorkOrderDetail:WorkOrderDetailID,PriceCodeID (外键),描述,UnitPrice,数量,小计,税,​​总计,WorkOrderID (外键)

  • PriceCode:PriceCodeID,ShortCode,Description,UnitPrice,Tax

我试图使用下面的声明,但我不确定如何使用GroupBy声明。

newInvoice.Details = _db.WorkOrderDetails
                        .Include("WorkOrder")
                        .Where(Function(wod) wod.WorkOrder.Date >= newInvoice.StartDate And 
                                             wod.WorkOrder.Date < newInvoice.EndDate And 
                                             wod.WorkOrder.ClientID = newInvoice.ClientID)
                        .GroupBy(...)
                        .ToList()

1 个答案:

答案 0 :(得分:1)

您可以通过

获取汇总结果
Dim aggregate = From wod in _db.WorkOrderDetails
                Where wod.WorkOrder.Date >= newInvoice.StartDate And 
                      wod.WorkOrder.Date < newInvoice.EndDate And 
                      wod.WorkOrder.ClientID = newInvoice.ClientID)
                Group wod By Key = New With { Key wod.PriceCodeID, Key Description }
                Into Group
                Select agg = Key.PriceCodeID,
                             Key.Description,
                             Quantity = Group.Sum(Function(wod) wod.Quantity),
                             Subtotal = Group.Sum(Function(wod) wod.Subtotal),
                             Total = Group.Sum(Function(wod) wod.Total)

您无法在此查询中直接创建新的WorkOrderDetail,因为EF不允许在LINQ查询中创建新的实体类型。但您可以使用aggregate.AsEnumerable()继续:

newInvoice.Details = aggregate.AsEnumerable()
                     .Select(Function (wod) New WorkOrderDetail ...)