简体   繁体   中英

how to sum a column in entity framework

I am trying to sum a column and get details member wise

My table data is

id   membername     cost
1   a               100
2   aa              100
3   a               100
4   aa                0
5   b               100

In Entity Framework I try to sum cost column and get result like this

membername             totalcost
a                      200
aa                     100
b                      100

then I am doing this

var result = from o in db.pruchasemasters.Where(d => d.memberid == d.membertable.id && d.entrydate >= thisMonthStart && d.entrydate <= thisMonthEnd)
                     group o by new { o.membertable.members } into purchasegroup
                     select new
                     {
                         membername = purchasegroup.Key,
                         total = purchasegroup.Sum(s => s.price)
                     };

How do I read the results and is my code right or not?

Something like that will work

    var result = db.pruchasemasters.GroupBy(o => o.membername)
                   .Select(g => new { membername = g.Key, total = g.Sum(i => i.cost) });

    foreach (var group in result)
    {
        Console.WriteLine("Membername = {0} Totalcost={1}", group.membername, group.total);
    }

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