In my ASP.NET Core-5 Entity Framework I have this model:
public class Sales
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }
public DateTime? SalesDate { get; set; }
}
DTO:
public class YearlyPercentDto
{
public decimal SalesTotal { get; set; }
public int SalesPercent { get; set; }
public string Year { get; set; }
}
public List<YearlyPercentDto> GetYearlySalesSummary()
{
var salesDetail = _context.sales
.GroupBy(o => new
{
Year = o.CreatedDate.Value.Year
})
.Select(u => new YearlyPercentDto
{
SalesPercent = u.Sum(x => x.Amount),
Year = u.Key.Year.ToString()
}).ToList();
return salesDetail;
}
I want to get the total_sales, percentage_sales for each year in the past 5 years as shown below:
Year (Past 5 Years) SalesTotal SalesPercent
2021 200000 18
2020 4300000
2019 1290000
2018 5400000
2017 3322220
How do I achieve this?
CodePudding user response:
I think I'd just pull the totals from the DB and have C# work out the percentage:
public List<YearlyPercentDto> GetYearlySalesSummary()
{
var salesDetail = _context.sales
.Where(s => o.CreatedDate > DateTime.Now.AddYears(-5)
.GroupBy(o => o.CreatedDate.Value.Year)
.Select(u => new YearlyPercentDto
{
SalesTotal = u.Sum(x => x.Amount),
Year = u.Key.ToString() //why is Year a string?
}
).ToList();
//grand total
var tot = salesDetail.Sum(s => s.SalesTotal);
//apply percentage to each element
salesDetail.ForEach(s => s.SalesPercent = (int)(100.0 * s.SalesTotal/tot));
return salesDetail;
}
There seems little point in bullying the DB to provide this info when C# can quickly work it out - the extra hoops to jump through to get the DB to do it don't seem worth it