简体   繁体   中英

How to get sum of fields in Entity Framework Core?

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

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}"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM