实体框架 - 从子记录中计算总和字段

时间:2017-11-20 06:34:54

标签: c# asp.net asp.net-mvc entity-framework entity-framework-core

我正在使用ASP.NET Core的实体框架核心,代码优先。

在我的应用中,我有发票,典型的InvoiceHeader - > InvoiceLine关系。InvoiceLine LineAmount个实体有一个InvoiceHeader字段,当我显示为列表时,我希望将其汇总并显示在TotalAmount上(因此我可以在查看发票列表时查看发票总额)

我猜我需要使用注释InvoiceHeader[NotMapped]实体添加InvoiceHeaderController.Index()属性。但如何最有效地填充它?

目前我的 // GET: InvoiceHeaders public async Task<IActionResult> Index() { ApplicationUser appUser = ConstantData.GetApplicationUser(_context, _userManager.GetUserId(User)); var applicationDbContext = _context.InvoiceHeader.Include(i => i.Customer).Include(i => i.CustomerBranch) .Where(i => i.CustomerID == appUser.CustomerID); return View(await applicationDbContext.ToListAsync()); } 是:

TotalAmount

有谁能告诉我计算(总和)此query_string = "" if conditionA: query_string += Q(income__gte=5000) if conditionB: query_string = Q(income=0) User.objects.filter(query_string) 属性的最有效方法是什么?

感谢。

2 个答案:

答案 0 :(得分:0)

选择sum作为单独的字段,您需要创建新的模型类,如下所示

public class InvoiceHeaderModel{
   public InvoiceHeader invoiceHeader{get;set;}
   public decimal TotalAmount {get;set;}
}

并以

的方式改变行动
// GET: InvoiceHeaders
public async Task<IActionResult> Index()
{
    ApplicationUser appUser = ConstantData.GetApplicationUser(_context, _userManager.GetUserId(User));
    var applicationDbContext =await _context.InvoiceHeader.Where(i =>i.CustomerID == appUser.CustomerID).ToListAsync();
    var data = applicationDbContext.Aggregate( new List<InvoiceHeaderModel>(),(invoiceHeaderModellist, it)=>{ invoiceHeaderModellist.Add(new InvoiceHeaderModel(){ InvoiceHeader =it,TotalAmount  = it.InvoiceLine.Sum(t=>t.LineAmount)}); return invoiceHeaderModellist;});
    return View(data);
}

在此操作中,我认为您不需要包含'Include(i =&gt; i.Customer).Include(i =&gt; i.CustomerBranch)'如果需要,您可以在封闭之前添加。

答案 1 :(得分:0)

我设法解决了这个问题。 Saneesh的建议很接近,但并不是我想要的。

我最终使用的代码是:

// GET: InvoiceHeaders

public async Task<IActionResult> Index()
{
    ApplicationUser appUser = ConstantData.GetApplicationUser(_context, _userManager.GetUserId(User));
            var applicationDbContext = _context.InvoiceHeader.Include(i => i.Customer).Include(i => i.CustomerBranch)
                .Where(i => i.CustomerID == appUser.CustomerID)
                .Select(i => new InvoiceListViewModel
                {
                    invoiceHeader = i,
                    TotalAmount = i.InvoiceLines.Sum(t => t.LineAmount)
                });
    return View(await applicationDbContext.ToListAsync());
}

感谢您的帮助Saneesh。

相关问题