简体   繁体   English

如何在实体框架中对一列进行求和

[英]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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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