将具有group by的SQL查询转换为LINQ查询

时间:2010-09-16 16:56:20

标签: linq-to-sql

我正在将SQL查询复制到LINQ中。 任何人都可以帮忙吗?

SQL:

 SELECT tblInvoice.lngID AS InvoiceID,
                tblInvoice.dtTimeStamp AS InvoiceDate,
                tblInvoice.strReference,
                tblInvoice.fltTotalValue,
                max(Project.ProjectID) AS ProjectID,
                max(Project.ProjectName) AS ProjectName,
                max(Project.Location) AS ProjectLocation
        FROM    tblInvoice INNER JOIN
                tblInvoiceLine ON tblInvoice.lngID = tblInvoiceLine.lngInvoiceID 
        WHERE   (tblInvoice.intStatus != 0)
        AND     (tblInvoice.lngPersonID = @PersonID)
        GROUP BY tblInvoice.lngID, tblInvoice.dtTimeStamp, strReference, fltTotalValue
        ORDER BY tblInvoice.lngID DESC

到目前为止LINQ:

var invoices = from inv in db.TblInvoices
    join invLine in db.TblInvoiceLines on inv.LngID equals invLine.LngInvoiceID
    where inv.IntStatus != 0
    where inv.LngPersonID == personID
    group inv by  new {inv.LngID,inv.DtTimeStamp,inv.StrReference,inv.FltTotalValue} into newInv

部分问题是我想做一个

select new Invoice(){
}

并建立我的自定义Invoice对象但是,我无法看到newInv中的任何属性。

任何人都可以提出建议吗?

1 个答案:

答案 0 :(得分:1)

我现在没有时间给出完整答案,但是:

  • 要获取密钥的属性,请使用newInv.Key.StrReference
  • 要获得聚合(例如最大值),请使用newInv.Max(x => x.ProjectId)

希望这足以让你前进。基本上,newInv将是条目的,并带有关联的密钥(按您分组的方式)。