Ormlite GROUP BY查询的正确语法是什么?

时间:2015-02-16 10:35:14

标签: sql-server ormlite-servicestack

将ServiceStack.OrmLite与SQL Server一起使用我试图通过映射实体对DTO对象实现GROUP BY查询,但我似乎无法使OrmLite语法正确。

映射的实体如下所示:

public class MacRequestLetter
{
    [PrimaryKey]
    public Guid BatchId { get; set; }
    [PrimaryKey]
    public Guid Id { get; set; }

    public DateTime LetterDate { get; set; }

    /*
       ... elided - more properties relevant to this entity ...
    */
}

如果我手动编写SQL,那就是我写的:

SELECT
     BatchId
    ,COUNT(*) AS LetterCount
    ,MAX(LetterDate) AS LetterDate
FROM
    dbo.MacRequestLetter
GROUP BY
    BatchId
ORDER BY
    LetterDate DESC

以下是我试图通过以下方式实现的Ormlite查询:

return db.Select<MacLetterBatch>(
    db.From<MacRequestLetter>()
        .Select(letter => new {
            BatchId = letter.BatchId,
            LetterCount = Sql.Count("*"),
            LetterDate = Sql.Max(letter.LetterDate)
        })
        .GroupBy(letter => letter.BatchId)
        .OrderByDescending(letter => Sql.Max(letter.LetterDate))
);

其中MacLetterBatch是一个DTO,其属性与查询的选择部分相匹配。

但是当我运行这个时,我收到一条带有消息Column 'MacRequestLetter.LetterDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

的SQL错误

发送到服务器的SQL是:

SELECT "MacRequestLetter"."BatchId", "MacRequestLetter"."LetterDate" 
FROM "MacRequestLetter"
GROUP BY "BatchId"
ORDER BY Max("LetterDate") DESC

以异常指出的方式显然是错误的。

有人能告诉我OrmLite代码有什么问题吗?什么代码可以实现我的目标?

0 个答案:

没有答案