In My project Enter data dayly Now I want have sum of record weekly or group data weekly, I try many methods, but got some error like:
.GroupBy( keySelector: d => __CurrentCulture_Calendar_0.GetWeekOfYear( time: d.ReportDate, rule: FirstDay, firstDayOfWeek: Saturday), elementSelector: d => d)'
This is my ViewModel (the same as Model) public class DataReportViewModels {
public int TotalPCRTest { get; set; }
public int TotalRapidTest { get; set; }
public int PosPCRTest { get; set; }
public int PosRapidTest { get; set; }
public int PatientInCovid { get; set; }
public int PatienPosInCovid { get; set; }
public int PatientInICU { get; set; }
public int TotalPosDeath { get; set; }
public int TotalOutpatients { get; set; }
[DataType(DataType.Date)]
public DateTime ReportDate { get; set; }
}
and in my PageModel
public IList<DataReportViewModels> ReportViewModelsw{ get; set; }
IQueryable<DataReportViewModels> dataw = _context.DataReports.GroupBy(d => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear
(d.ReportDate, CalendarWeekRule.FirstDay, DayOfWeek.Saturday))
.Select(dat => new DataReportViewModels
{
//ReportDate = dat.Key,
TotalPCRTest = dat.Sum(x => x.TotalPCRTest),
TotalRapidTest = dat.Sum(x => x.TotalRapidTest),
PosPCRTest = dat.Sum(x => x.PosPCRTest),
PosRapidTest = dat.Sum(x => x.PosRapidTest),
PatientInCovid = dat.Sum(x => x.PatientInCovid),
PatienPosInCovid = dat.Sum(x => x.PatienPosInCovid),
PatientInICU = dat.Sum(x => x.PaatientInICU),
TotalPosDeath = dat.Sum(x => x.TotalPosDeath),
TotalOutpatients = dat.Sum(x => x.TotalOutpatients)
}).OrderByDescending(x => x.ReportDate);
ReportViewModelsw = dataw.ToList();
Update my query
var dataw = _context.DataReports.AsEnumerable().Where(x => x.Id > 1).GroupBy(d =>
// ReportDate = d.ReportDate,
(d.ReportDate.Day - 10) / 7)
.Select(dat => new DataReportViewModels
{
TotalPCRTest = dat.Sum(x => x.TotalPCRTest),
TotalRapidTest = dat.Sum(x => x.TotalRapidTest),
PosPCRTest = dat.Sum(x => x.PosPCRTest),
PosRapidTest = dat.Sum(x => x.PosRapidTest),
PatientInCovid = dat.Sum(x => x.PatientInCovid),
PatienPosInCovid = dat.Sum(x => x.PatienPosInCovid),
PatientInICU = dat.Sum(x => x.PaatientInICU),
TotalPosDeath = dat.Sum(x => x.TotalPosDeath),
TotalOutpatients = dat.Sum(x => x.TotalOutpatients)
});
And my table is normal table
<table class="table table-striped table-hover">
<caption>weekly report</caption>
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.ReportViewModelsw[0].TotalPCRTest)
</th>
...
</tr>
</thead>
<tbody>
@foreach (var item in Model.ReportViewModelsw)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.TotalPCRTest)
</td>
....
</tr>
}
</tbody>
</table>
Date time extention
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
}