使用 groupBy 和月份将 sql 查询转换为 linq

Transform sql query to linq with groupBy and months

我有以下查询:

select concat(Left(DateName(month,[date]),3), ' ', Year([date])), 
    sum(TotalAttendants) as Total,
    Sum(FemaleAttendants) as Women,
    Sum(MaleAttendants) as Men
from dbo.Events
where IsDeleted=0 and EventTypeId = 1
group by concat(Left(DateName(month,[date]),3), ' ', Year([date]))

我想将它转换为 c# linq lambda 表达式。

我试过这样的事情:

var response = await _context.Events
                             .Where(x => !x.IsDeleted && x.EventTypeId == Domain.Enums.EventTypes.DirectBeneficiaries)
                             .GroupBy(x => x.Date)
                             .Select(x => new EventViewData
                                {
                                    MaleAttendants = x.Sum(u => u.MaleAttendants),
                                    FemaleAttendants = x.Sum(u => u.FemaleAttendants),
                                    TotalAttendants = x.Sum(u => u.TotalAttendants),
                                    MonthName = x.Key.ToString("00")
                                }).ToListAsync();

我得到的结果与我在 mssql 管理工作室中得到的结果不同。

如果您需要有关数据结构和 table 事件的更多信息,这里是我的另一个 Whosebug 主题:

我认为你应该按月和年分组,然后再进行格式化(concat 等)(如果需要的话)。

select 
...
from dbo.Events
..
group by Month([date]), Year([date]))

然后在linq中你可以:

...
.GroupBy(x => new { Year = x.Date.Year, Month = x.Date.Month } )
.Select(x => new  // Note no type name
{
   MaleAttendants = x.Sum(u => u.MaleAttendants),
   FemaleAttendants = x.Sum(u => u.FemaleAttendants),
   TotalAttendants = x.Sum(u => u.TotalAttendants),
   Month = x.Key.Month,
   Year = x.Key.Year
})
.ToListAsync() // Hit the db
.Select( x => new EventViewData
{
   x.MaleAttendants
   x.FemaleAttendants
   x.TotalAttendants
   MonthName = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(x.Month)
   ...
}

我认为 EF 不支持 GetAbbreviatedMonthName,因此我们需要在 ToListAsync 之后进行。