Entity framework : Return 按同一查询中某些列的值和总和分组

Entity framework : Return grouped by value and sum of some columns in the same query

我有一个 table,我想在实体框架工作中执行以下操作:

1- Return 对象中的一些列不是所有列(我为这个新类型创建了新的 class 只包含我需要的列和其中的 return 值 select声明。

2- Return 列应按某些列分组,其中两列将包含计数值。 (这是我的问题)。

更多说明:我需要将以下查询映射到 Entity Framework 中我的数据集的可查询对象:

select SUM (Col1) SUM_Col1, SUM (Col2) SUM_Col2, COUNT (*) RECORDS, Col3, Col4, Col5
from myTable
where col3 = 'some value'
group by Col3, Col4, Col5;

我的分组试验如下:

        query = from record in context.tables
                group record by new
                {
                    record.Col3,
                    record.Col4,
                    record.Col5,
                } into g
                select new QueryResult
                {
                    Col1 = (need Sum of Col1 here),
                    Col2 = (need Sumn of Col2 here),
                    Col3 = g.Key.Col3,
                    Col4 = g.Key.Col4,
                    Col5 = g.Key.Col5,
                    Col6 = ( need count of grouped records here)

                };

使用Sum and Count

 query = from record in context.tables
                group record by new
                {
                    record.Col3,
                    record.Col4,
                    record.Col5,
                } into g
                select new QueryResult
                {
                    Col1 = g.Sum(x => x.Col1),
                    Col2 = g.Sum(x => x.Col2),
                    Col3 = g.Key.Col3,
                    Col4 = g.Key.Col4,
                    Col5 = g.Key.Col5,
                    col6 = g.Count()

                };

试试这个查询:

var query = context.tables.GroupBy(r=>new{r.Col3, r.Col4, r.Col5})
                          .Select(g=>{
                                         Col1 = g.Sum(c=>c.Col1),
                                         Col2 = g.Sum(c=>c.Col2),
                                         Col3 = g.Key.Col3,
                                         Col4 = g.Key.Col4,
                                         Col5 = g.Key.Col5,
                                         Col6 = g.Count
                                     })

也许这个例子可以帮助你,它对两列求和并与另一列进行连接 table

from e in _context.LearnResults
 join c in _context.Country on e.CountryId equals c.CountryId
 where c.DomainId.Equals("xx")
 group e by e.Country.Name into newCountry
 let Approved = newCountry.Sum(e => e.Approved)
 let Total = newCountry.Sum(e => e.Total)
 select new LearnResults() { CountryName = newCountry.Key, Approved= Approved, Total=Total };