简体   繁体   中英

Entity Framework - GroupBy, OrderBy, Sum

I am trying to rewrite this query in Entity Framework (method syntax) but I can't. I don't understand what needs to be done first.

My Postgres query:

select id, Sum(yellow_hour) "yellow_hour"
from my_table
group by id
where date_part('day', date::timestamptz - '2022-10-30 00:00:00.000 +0200'::timestamptz) > 0
order by yellow_hour desc 
limit 20

My attempt:

var sensors = dbContext.mytable
                       .Where(x => x.Date >= instantStartDate && x.Date <= instantEndDate)
                       .GroupBy(x => x.id)
                       .ToList();

Error:

Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side.

Although not having access to a compiler right now there might be some typo's but you will get the idea with the current LINQ query.

var queryDate = DateTime.Parse("2022-10-30 00:00:00.000 +0200");
db.my_table.Where(t=>t.date > queryDate).GroupBy(t => t.id).
              Select(g => new 
                {
                    g.Key, 
                    SUM = g.Sum(s=>s.yellow_hour)
                }).OrderByDescending(g=>g.SUM).Take(20);

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