Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Group By Sum

This is a relatively new area for me. I have two entities: Inquiries and Categories.

Each Inquiry has a category and a property indicating an integer value (called TotalTimeSpent), and each category has multiple inquiries.

What I want to do is generate a view that is grouped by categories while summing all the inquiries in that one category.

My code at the moment is:

var catgroup = db.CATEGORies.GroupBy(i => i.CATNAME).Sum(c => c.)

Obviously each grouping has multiple inquiries in it, so when I am doing the c=> c. it is not bringing back the property that I need to sum with only the group extensions (like FirstOrDefault).

How do I continue from here so I can sum TotalTimeSpent for each inquiry based on the above grouping?

like image 564
Trinitrotoluene Avatar asked Sep 04 '26 17:09

Trinitrotoluene


1 Answers

Try this instead:

var catgroup = db.CATEGORies.GroupBy(c => c.CATNAME)
    .Select(g => new {
        g.Key, 
        SUM = g.Sum(s => s.Inqueries.Select(t => t.TotalTimeSpent).Sum())
    });
like image 141
Giorgi Nakeuri Avatar answered Sep 07 '26 11:09

Giorgi Nakeuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!