如何在 Entity Framework Core 中做 count 等聚合函数
How to do aggregate functions such as count in Entity Framework Core
我有这个 SQL 我想在 Entity Framework Core 2.1 中执行:
Select ItemTypeId, Count(ItemTypeId) as Count from Items i
where i.ParentId = 2
group by ItemTypeId
我该怎么做?
这是我想出来的,但是 returns 零:
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
您不需要 Count = g.Count(i=> i.ItemTypeId == g.Key.ItemTypeId)
,而是使用 g.Count()
。
我有这个 SQL 我想在 Entity Framework Core 2.1 中执行:
Select ItemTypeId, Count(ItemTypeId) as Count from Items i
where i.ParentId = 2
group by ItemTypeId
我该怎么做?
这是我想出来的,但是 returns 零:
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
您不需要 Count = g.Count(i=> i.ItemTypeId == g.Key.ItemTypeId)
,而是使用 g.Count()
。