mycode的:
//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都有日期和时间,我想按日期分组,我该怎么做
答案 0 :(得分:45)
使用EntityFunctions.TruncateTime
Method (Nullable<DateTime>
)。它将被转换为生成的SQL查询中的TRUNCATETIME()
TSQL函数,它可以满足您的需求:
返回表达式,时间值被截断。
所以你的代码应该如下:
//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() };
答案 1 :(得分:0)
var result = from s in entitiesModel.TvysFuelTankDatas
orderby s.Datetime ascending
group s by new { y = s.Datetime.Year, m = s.Datetime.Month + "/", d = s.Datetime.Day + "/" } into g
select new WellDrillData { Date = Convert.ToDateTime(g.Key.d.ToString() + g.Key.m.ToString() + g.Key.y.ToString()), Depth = (double)g.Sum(x => x.Difference) };
List<WellDrillData> dailyFuelConsumptions = result.ToList();
答案 2 :(得分:0)
这里有一种更简单的方法可以为以后的实体框架版本做到这一点。
var query = Data
.GroupBy(o => new { EventDate = o.EventDate.Date })
.Select(s => new SalesData()
{
EventDate = s.Key.EventDate,
Amount = s.Sum(o => o.Amount),
Qty = s.Sum(o => o.Qty),
RefundAmount = s.Sum(o => o.RefundAmount),
RefundQty = s.Sum(o => o.RefundQty),
})
.OrderBy(o => o.EventDate)
.ToList();
返回查询;