Search code examples
entity-frameworkentity-framework-6

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?


Solution

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