How to get sum of fields in Entity Framework Core? [duplicate]

I have a table like this in SQL Server and a model class in C# with Entity Framework Core:

id relatedId dec1 dec2
1 1 540000 250000
2 1 255000 200000
3 2 100 200
4 2 500 400

Now I want get sum of dec1 and dec2 for relatedId 1 and 2 seperatly. like this:

relatedId1 sum dec1 = 7950000 and sum dec2 = 450000
relatedId2 sum dec1 - 600 and dec2 = 600

in my C# code.

Thanks


Solution 1:

Try using the GroupBy, and Sum , like so,

var summ = entName.GroupBy(t => t.relatedId)
                           .Select(t => new
                           {
                               relatedId = t.Key,
                               dec1Sum = t.Sum(d => d.dec1),
                               dec2Sum = t.Sum(d => d.dec2),
                           }).ToList();

//print the results
summ.ForEach(t => Console.WriteLine($"relatedId {t.relatedId}, sum for dec1 : {t.dec1Sum}, sum for dec2 : {t.dec2Sum}"));