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

1k views Asked by At

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

There are 1 answers

0
Vivek Nuna On BEST ANSWER

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