要实现显示每个月/年类别的费用总计行和每月总费用,您可以按照以下步骤进行操作:
创建一个ASP.Net Core MVC项目。
安装所需的NuGet包:
创建一个表示费用的实体类:
public class Expense
{
public int Id { get; set; }
public string Category { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
}
public class ExpenseContext : DbContext
{
public ExpenseContext(DbContextOptions options) : base(options)
{
}
public DbSet Expenses { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
}
public class ExpenseController : Controller
{
private readonly ExpenseContext _context;
public ExpenseController(ExpenseContext context)
{
_context = context;
}
public IActionResult Index()
{
var monthlyTotal = _context.Expenses
.GroupBy(e => new { e.Category, e.Date.Year, e.Date.Month })
.Select(g => new
{
Category = g.Key.Category,
Year = g.Key.Year,
Month = g.Key.Month,
Total = g.Sum(e => e.Amount)
})
.OrderBy(g => g.Year)
.ThenBy(g => g.Month)
.ToList();
var yearlyTotal = _context.Expenses
.GroupBy(e => new { e.Category, e.Date.Year })
.Select(g => new
{
Category = g.Key.Category,
Year = g.Key.Year,
Total = g.Sum(e => e.Amount)
})
.OrderBy(g => g.Year)
.ToList();
ViewBag.MonthlyTotal = monthlyTotal;
ViewBag.YearlyTotal = yearlyTotal;
return View();
}
}
@model IEnumerable
Monthly Total
Category
Year
Month
Total
@foreach (var item in Model)
{
@item.Category
@item.Year
@item.Month
@item.Total
}
Yearly Total
Category
Year
Total
@foreach (var item in ViewBag.YearlyTotal)
{
@item.Category
@item.Year
@item.Total
}
以上代码将从数据库中检索费用数据,并使用efcore执行分组和求和操作,然后将结果传递给Razor视图进行显示。在视图中,您可以使用循环来遍历结果并在表格中显示数据。