关于子元素的LINQ Sum查询

时间:2016-09-29 20:15:23

标签: vb.net entity-framework linq sum aggregate

我试图在一个月内为我的申请汇总发票。有两个对象;一个Invoice对象和一个InvoiceDetails对象。 Invoice对象包含有关发票(日期,客户等)的详细信息,而InvoiceDetails对象包含每张发票的行项目(数量,价格,税等)。我想根据发票中的钱来计算每个月的收入。我可以使用GroupBy方法按日期汇总发票,但我似乎无法在InvoiceDetails中添加订单项,这会为我提供当月的总收入。对象列在下面。

发票类:

Public Class Invoice

    Public Property InvoiceID As Integer
    Public Property InvoiceDate As Date
    Public Property DueDate As Date
    Public Property Details As List(Of InvoiceDetail)
    Public Property Client As Client
    Public Property ClientID As Integer

End Class

InvoiceDetails类:

Public Class InvoiceDetail

    Public Property InvoiceDetailID As Integer
    Public Property Description As String
    Public Property UnitPrice As Decimal
    Public Property Quantity As Integer
    Public Property Subtotal As Decimal
    Public Property Tax As Decimal
    Public Property Total As Decimal
    Public Property Invoice As Invoice

End Class

我当前的LINQ查询如下:

Public Function GetRevenueByMonth(Year As Integer, Month As Integer) As DataSourceResult

    Dim StartDate As New Date(Year, Month, 1)
    Dim EndDate As Date = StartDate.AddMonths(1).AddSeconds(-1)

    Dim Revenue = _db.Invoices.Include(Function(i) i.InvoiceDetails
        .Select(Function(invd) invd.Total))
        .Where(Function(i) i.InvoiceDate >= StartDate And i.InvoiceDate <= EndDate)
        .GroupBy(Function(i) i.InvoiceDate.Date)
        .Select(Function(r) New With {
            .Date = r.Key, .Revenue = r.Sum(Function(invd) invd.Total)
        })

End Function

该功能看起来很好,直到最后一行。我收到了“Total&#39;的错误不是InvoiceDetail&#39;的成员。我希望invd引用子元素,而不是它引用父元素。如何使这个LINQ查询工作?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作

 Dim Revenue = _db.InvoicesDetails
        .Where(Function(i) i.Invoice.InvoiceDate >= StartDate And i.Invoice.InvoiceDate <= EndDate)
        .GroupBy(Function(i) i.Invoice.InvoiceDate.Date)
        .Select(Function(r) New With {
            .Date = r.Key, .Revenue = r.Sum(Function(invd) invd.Total)
        })

希望这会对你有所帮助