您的位置:首页 > 其它

EntityFramework Linq 按年月统计查询

2016-09-20 17:23 316 查看
Expression<Func<Operator, bool>> wh = c => c.DimissionId != null;

DateTime dtValueStart = DateTime.MinValue;
DateTime dtValueEnd = DateTime.MinValue;
if (!string.IsNullOrEmpty(startdate) && DateTime.TryParse(startdate, out dtValueStart))
{
//重置为当月第一天
dtValueStart = new DateTime(dtValueStart.Year, dtValueStart.Month, 1);
wh = wh.And(c => DbFunctions.TruncateTime(c.DimissionDate) >= DbFunctions.TruncateTime(dtValueStart));
}
if (!string.IsNullOrEmpty(enddate) && DateTime.TryParse(enddate, out dtValueEnd))
{
//重置为当月最后一天
dtValueEnd = new DateTime(dtValueEnd.Year, dtValueEnd.Month, 1).AddMonths(1).AddDays(-1);
wh = wh.And(c => DbFunctions.TruncateTime(c.DimissionDate) <= DbFunctions.TruncateTime(dtValueEnd));
}

var result = operatorService.GetByFilter(wh).GroupBy(c => new { c.DimissionDate.Value.Year, c.DimissionDate.Value.Month }).Select(g => new DimissionYearMonthlyVM
{
Year = g.Key.Year,
Month = g.Key.Month,
DimissionQty = g.Count()

}).OrderBy(c => new { c.Year, c.Month }).ToList();

1、日期查询条件需要使用DbFunctions.TruncateTime
转换一下

2、统计查询取值字段按照GroupBy中的字段
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: