I have code snippet below for grouping records for last 12 months and it works properly but I just noticed that empty months is not included. Where did I go wrong? Thanks in advance
public IQueryable<DashboardGrouping> DashboardStats()
{
var yearAgo = DateTime.Now.AddYears(-1);
var date = new DateTime(yearAgo.Year, yearAgo.Month, 1);
var items = context.Set<Transaction>()
.Where(x => x.IsActive &&
x.CreatedAt.HasValue && x.CreatedAt.Value.Date >= date.Date && x.PaymentStatusId ==
PaymentStatus.Completed)
.Include(x => x.Payment)
.Include(x => x.Branch)
.AsNoTracking()
.Select(x => new
{
Year = x.CreatedAt.Value.Year,
Month = x.CreatedAt.Value.Month,
CashAmount = x.Payment.CashAmount,
CardAmount = x.Payment.CardAmount,
})
.GroupBy(x => new
{
Year = x.Year,
Month = x.Month,
})
.Select(x => new DashboardGrouping
{
Year = x.Key.Year,
Month = x.Key.Month,
TotalSale = x.Sum(s => s.CashAmount + s.CardAmount)
});
return items;
}
You can do client-side postprocessing and enrich result with missing records.
Helper function for generating months:
Postprocessing: