繁体   English   中英

在实体框架的关联表中返回一行和某些行的总和

[英]Return a row and sum of some Rows in the Associated table in entity framework

我有两个桌子

Invoice(**Id** , date , customerName, customerPhone, paid , status)

InvoiceItem(**Id** , ItemId , quantity , price , invoiceId )

现在我的问题是

结合整行发票,我如何从invoiceItems表中获取该发票的总金额?

创建一个视图模型以保存您的结果。

    public class InvoiceViewModel
    {
        public Invoice Invoice { get; set; }
        public double Total { get; set; }
    }

    public InvoiceViewModel GetInvoice(int invoiceID)
    {
            var sum = yourContext.InvoiceItems
                .Where(x => x.invoiceId == invoiceID)
                .Select(x => x.quantity * x.price)
                .Aggregate((a, b) => a + b);

            return yourContext.Invoices
                .FirstOrDefault(x => x.Id == invoiceID)
                .Select(invoice => new InvoiceViewModel
                {
                    Invoice = invoice,
                    Total = sum
                });
    }

然后使用它:

var someInvoice = GetInvoice(1);
var name = someInvoice.Invoice.customerName;
var total = someInvoice.Total;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM