Basic Lambda groupby expression for totals, foreach usage in EF

        private async void updateTotalAmounts(Guid id)
        {
            
            var result = _context.SalesOrderLine.GroupBy(o => o.SalesOrderID)
                 .Select(g => new { SalesOrderID = g.Key,
                     TotalAmount = g.Sum(i => i.LineAmount),
                     TotalDiscAmount = g.Sum(i => i.TotalDiscAmount) });

            foreach (var group in result)
            {
                var salesOrder = _context.SalesOrder.SingleOrDefault(m => m.ID == id);
                salesOrder.TotalAmount = group.TotalAmount;
                salesOrder.TotalDiscAmount = group.TotalDiscAmount;
                _context.Update(salesOrder);
                await _context.SaveChangesAsync();
            }
           

        }

Leave a Reply

Your email address will not be published. Required fields are marked *