如何使用实体框架按日期分组而不是按时间分组 [英] how to use entity framework to group by date not date with time
本文介绍了如何使用实体框架按日期分组而不是按时间分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码:
//get data
var myData = from log in db.OperationLogs
group log by log.CreateTime.Date into g
orderby g.Key
select new { CreateTime = g.Key, Count = g.Count() };
此代码将引发异常,例如实体框架不支持get Date操作.
因为log.createtime
都有日期和时间,所以我想按日期分组,我应该怎么做
this code will throw an exception like entity framework does not support get Date operation.
because log.createtime
both have date and time, i want to group by date, how should i do
推荐答案
Use EntityFunctions.TruncateTime
Method (Nullable<DateTime>
). It will be transalated into TRUNCATETIME()
TSQL function in generated SQL query, which does what you need:
返回表达式,时间值被截断.
Returns the expression, with the time values truncated.
因此,您的代码应如下所示:
So your code should be as follows:
//get data
var myData = from log in db.OperationLogs
group log by EntityFunctions.TruncateTime(log.CreateTime) into g
orderby g.Key
select new { CreateTime = g.Key, Count = g.Count() };
这篇关于如何使用实体框架按日期分组而不是按时间分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文