Laden...

Linq sortierung und summierung

Erstellt von Notte vor 2 Jahren Letzter Beitrag vor 2 Jahren 268 Views
N
Notte Themenstarter:in
1 Beiträge seit 2022
vor 2 Jahren
Linq sortierung und summierung

Hallo!!!

Ich bin neu hier und hätte eine frage?
ich habe in der Datenbank zwei Tabellen

  1. **Document ** mit Gesamtrechnung = Total
  2. PaymentInformation mit Einzelne Rechnungen = PaymentSum

Beziehung ist eine 1:n wobei die DocumentId in der PaymentInformation liegt.

Nun würd ich gerne die einzelnen Rechnungen in die Gesamtrechnung speichern. Die einzelnen Rechnungen sind sogar schon mit der Id der Gesamtrechnung verknüpft, aber leider bekomme ich es einfach nicht hin, hier eine abfrage zu machen.


// POST: api/PaymentInformations
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost("new/{eId}")]
        public async Task<ActionResult<PaymentInformation>> PostpaymentInformations(long eId, PaymentInformation paymentInformation)
        {
            Document document = await _context.Documents.FindAsync(eId);
   
           document.Total = _context.PaymentInformations
                                .Where(b => b.Document.Id == eId)
                                .Sum(a => a.PaymentSum);


            foreach (var item in _context.PaymentInformations)
            {
                System.Console.WriteLine(item.PaymentSum);
                System.Console.WriteLine(item.DocumentId);
            }
           
            _context.PaymentInformations.Add(paymentInformation);

            document.addPaymentInformation(paymentInformation);

            await _context.SaveChangesAsync();
            return CreatedAtAction("GetpaymentInformations", new { id = paymentInformation.Id }, paymentInformation);     
        }

P
441 Beiträge seit 2014
vor 2 Jahren

Die Controller Action macht eigentlich etwas anderes oder? Ich bin etwas verwirrt 🙂

Was genau klappt denn nicht?


 Document document = await _context.Documents.FindAsync(eId);
// document != null ?
           document.Total = _context.PaymentInformations
                                .Where(b => b.Document.Id == eId)
                                .Sum(a => a.PaymentSum);

await _context.SaveChangesAsync();

Sollte prinzipiell das machen, was du möchtest. Die PaymentSum aller PaymentInformations dieses einen Dokuments auslesen und aufsummieren.

Da du aber die neue, übergebene Entität erst danach in die Datenbank speicherst wird diese fehlen.

Ich empfehle einen Blick in den Artikel über [Artikel] Drei-Schichten-Architektur