简体   繁体   English

实体框架。 SQL分组依据到EF分组依据

[英]Entity Framework. SQL Group By to EF Group By

I am trying to define a standard way to group by year, by month, by day, by hour, etc ... 我正在尝试定义一种按年,按月,按天,按小时等分组的标准方式...

By reading some SQL documentation it seems the most efficient way would be to use: 通过阅读一些SQL文档,看来最有效的方法是使用:

GROUP BY dateadd(month, datediff(month, 0, CreatedDate), 0)

Note the "month", "year", ... 注意“月”,“年”,...

I then tried to replicate this using: 然后,我尝试使用以下方法来复制它:

.GroupBy(x => SqlFunctions.DateAdd("month", SqlFunctions.DateDiff("month", 0, x.Created), 0))

.GroupBy(x => EntityFunctions.AddMonths(EntityFunctions.DiffMonths(0, x.Created)))

However, both expression failed to compile ... 但是,两个表达式都无法编译...

And I am not sure if this is the way to do it? 我不确定这是否是这样做的方法吗?

How can I correctly replicate that SQL code line in EF? 如何在EF中正确复制该SQL代码行?

I don't understand Why would you want to use the standard sql to do that any way, however this can be done easily using LINQ and it would be more standard , grouping by an anonymous type for example like this: 我不明白您为什么要使用标准sql以任何方式进行此操作,但是可以使用LINQ轻松完成,这将更加标准 ,按匿名类型进行分组,例如:

.GroupBy( x => new 
               {
                  month = x.CreatedDate.Month,
                  year = x.CreatedDate.Year,
                  ...
               });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM