如何将 group by SQL 查询转换为 Entity Framework

How to convert group by SQL query to Entity Framework

请指导我如何将此查询转换为 Entity Framework 查询?

select 
    sum(Amount), convert(varchar(10), CreatedOn, 120)
from 
    [TableName]
group by 
    convert(varchar(10), CreatedOn, 120)
order by 
    convert(varchar(10), CreatedOn, 120)

谢谢。

可以使用 linq 来完成:

var results = TableName.GroupBy(x => x.CreatedOn).OrderBy(x=>x.CreatedOn).ToList();

假设您的 CreatedOn 列的类型是日期时间,您可以在这种情况下充分利用 DbFunctions.TruncateTime:

ICollection<GroupedRow> result = context.TableName.GroupBy(t => DbFunctions.TruncateTime(t.CreatedOn))
            .Select(g => new GroupedRow()
            {
                Sum = g.Sum(t => t.Amount),
                DateCreatedOn = g.Key
            }).OrderBy(c => c.DateCreatedOn).ToList();

其中 GroupedRow 是:

class GroupedRow
{
    public int Sum { get; set; }
    public DateTime? DateCreatedOn { get; set; }
}

虽然 linq to entities 查询看起来很干净,但为 Sql Server 2014 生成的 sql 将如下所示:

SELECT 
[Project1].[C3] AS [C1], 
[Project1].[C2] AS [C2], 
[Project1].[C1] AS [C3]
FROM ( SELECT 
    [GroupBy1].[K1] AS [C1], 
    [GroupBy1].[A1] AS [C2], 
    1 AS [C3]
    FROM ( SELECT 
        [Extent1].[K1] AS [K1], 
        SUM([Extent1].[A1]) AS [A1]
        FROM ( SELECT 
            convert (datetime2, convert(varchar(255), [Extent1].[CreatedOn], 102) ,  102) AS [K1], 
            [Extent1].[Amount] AS [A1]
            FROM [dbo].[TableName] AS [Extent1]
        )  AS [Extent1]
        GROUP BY [K1]
    )  AS [GroupBy1]
)  AS [Project1]
ORDER BY [Project1].[C1] ASC

根据 CAST and CONVERT (Transact-SQL) 文档,102 样式表示格式 "yyyy.mm.dd"。

至少,您可以在 UI 中根据需要格式化日期,因为您最终会得到一个 DateTime 对象,但在您的情况下,您可能想要使用 Date.ToString("yyyy-MM-dd") .