简体   繁体   中英

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

I am having two tables as

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

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

now my question is that,

In combination with whole row of invoice how would i get total amount of that invoice from invoiceItems Table?

Make a view model to hold your results.

    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
                });
    }

Then to use it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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