EntityFramework Linq 按年月统计查询

Expression> 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中的字段

你可能感兴趣的:(C#Web開發,知识点(做项目),EF)