【发布时间】:2020-03-31 07:00:21
【问题描述】:
我还能够按月/年排序并获得总计或按类别排序并获得该类别的总金额 - 但无法弄清楚如何将它们组合在一起。
这将创建允许月份组的操作
public async Task<IActionResult> ExpensesPaymentList()
{
var model = _context.Requests.Include(r => r.Product)
.ThenInclude(r => r.ProductSubcategory)
.ThenInclude(r => r.ParentCategory)
.GroupBy(r => new
{
Month = r.ParentRequest.OrderDate.Month,
Year = r.ParentRequest.OrderDate.Year,
})
.Select(g => new MonthlyTotalsViewModel
{
Month = g.Key.Month,
Year = g.Key.Year,
GrandTotal = g.Sum(r => r.Cost)
})
.OrderByDescending(a => a.Year)
.ThenByDescending(a => a.Month)
.ToList();
return View(await model.ToListAsync());
}
这会创建允许类别组的操作
public ActionResult ExpensesPaymentList()
{
var model = _context.Requests.Include(r => r.Product)
.ThenInclude(r => r.ProductSubcategory)
.ThenInclude(r => r.ParentCategory)
.AsEnumerable()
.GroupBy(r => new
{
ParentCategory = r.Product.ProductSubcategory.ParentCategory,
})
.Select(g => new ExpensesPaymentListViewModel
{
ParentCategory = g.Key.ParentCategory,
Total = g.Sum(r => r.Cost)
})
.ToList();
return View(model);
}
我的视图模型:
public class ExpensesPaymentListViewModel
{
public ParentCategory ParentCategory { get; set; }
public double Total { get; set; }
}
public class MonthlyTotalsViewModel
{
public int Month { get; set; }
public int Year { get; set; }
public double GrandTotal { get; set; }
}
我愿意接受任何建议或尝试全新的东西 - 我已经坚持了好几天了。 谢谢!
编辑: 我还尝试在选择中使用 where 并对各种类别进行硬编码并将它们绑定到 viewModel 但是 Linq 说它不是有效的查询。见下文
public async Task<IActionResult> ExpensesPaymentList()
{
var model = _context.Requests.Include(r => r.Product)
.ThenInclude(r => r.ProductSubcategory)
.ThenInclude(r => r.ParentCategory)
.GroupBy(r => new
{
Month = r.ParentRequest.OrderDate.Month,
Year = r.ParentRequest.OrderDate.Year,
})
.Select(g => new MonthlyTotalsViewModel
{
Month = g.Key.Month,
Year = g.Key.Year,
PlasticsTotal = g.Where(g => g.Product.ProductSubcategory.ParentCategory.ParentCategoryID == 1).Sum(r => r.Cost),
ReagentsTotal = g.Where(g => g.Product.ProductSubcategory.ParentCategory.ParentCategoryID == 2).Sum(r => r.Cost),
//and so on for the rest of my parentcategories
GrandTotal = g.Sum(r => r.Cost)
})
.OrderByDescending(a => a.Year)
.ThenByDescending(a => a.Month)
.ToList();
return View(await model.ToListAsync());
}
【问题讨论】:
标签: c# linq model-view-controller