LINQ聚合/ SUM分组问题

时间:2010-05-24 06:16:55

标签: sql vb.net linq aggregate sum

我无法将传统的SQL聚合查询转换为LINQ查询。基本数据转储的工作原理如下:

    Dim result =
    (From i As Models.InvoiceDetail In Data.InvoiceDetails.GetAll
    Join ih As Models.InvoiceHeader In Data.InvoiceHeaders.GetAll On i.InvoiceHeaderID Equals ih.ID
    Join p As Models.Product In Data.Products.GetAll On i.ProductID Equals p.ID
    Join pg As Models.ProductGroup In Data.ProductGroups.GetAll On p.ProductGroupID Equals pg.ID
    Join gl As Models.GLAccount In Data.GLAccounts.GetAll On pg.GLAccountSellID Equals gl.ID
    Where (gl.ID = GLID)
    Select ih.Period,i.ExtendedValue)

我需要真正获得的是ih.Period(1到12之间的值)和i.ExtendedValue的相应聚合值。当我尝试Group ih时,我得到的错误是我超出范围/上下文,我不知道怎么回事。

1 个答案:

答案 0 :(得分:2)

为简单起见,请尝试将其拆分为两个不同的查询。例如:

From result In
    (From i As Models.InvoiceDetail In Data.InvoiceDetails.GetAll
    Join ih As Models.InvoiceHeader In Data.InvoiceHeaders.GetAll On i.InvoiceHeaderID Equals ih.ID
    Join p As Models.Product In Data.Products.GetAll On i.ProductID Equals p.ID
    Join pg As Models.ProductGroup In Data.ProductGroups.GetAll On p.ProductGroupID Equals pg.ID
    Join gl As Models.GLAccount In Data.GLAccounts.GetAll On pg.GLAccountSellID Equals gl.ID
    Where (gl.ID = GLID) And (ih.FinancialYear = FinancialYear)
    Select ih.Period, i.ExtendedValue)
Group By result.Period Into Sum(result.ExtendedValue)