Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 431
Dharmeshsharma Avatar asked Jan 16 '13 00:01

Dharmeshsharma


1 Answers

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);
    }
like image 140
Vitalik Avatar answered Sep 25 '22 01:09

Vitalik