如何在Entity Framework Core中进行聚合功能(例如计数)

时间:2018-09-16 13:48:17

标签: entity-framework-core entity-framework-core-2.1

我有一个要在Entity Framework Core 2.1中执行的SQL:

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

我该怎么做?

这是我想出的,但返回零:

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();

我唯一能找到的例子是here

1 个答案:

答案 0 :(得分:1)

您不需要Count = g.Count(i=> i.ItemTypeId == g.Key.ItemTypeId),而使用g.Count()