How to do aggregate functions such as count in Entity Framework Core

entity-framework-core entity-framework-core-2.1

Question

I have this SQL that I would like to execute in Entity Framework Core 2.1:

Select ItemTypeId, Count(ItemTypeId) as Count from Items i 
where i.ParentId = 2
group by ItemTypeId 

How do I do that?

This is what I came up with, but it returns zero:

var query = this._context.Items.Where(a => a.ParentId == 2)
.GroupBy(i => new { i.ItemTypeId })
.Select(g => new { g.Key.ItemTypeId, Count = g.Count(i=> i.ItemTypeId == g.Key.ItemTypeId) });

var items = query.ToList();

The only example I could find was here

1
0
9/16/2018 1:48:17 PM

Accepted Answer

You don't need Count = g.Count(i=> i.ItemTypeId == g.Key.ItemTypeId), instead use g.Count().

1
9/17/2018 4:31:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow