C# 从EF返回两列Id和count作为字典<;int,int>;

C# 从EF返回两列Id和count作为字典<;int,int>;,c#,entity-framework,linq-to-entities,C#,Entity Framework,Linq To Entities,我在两个表之间有一个FK关系,但为了进行此查询,我需要获取每个FK的行数 例如,我有一个CareTaker表,其中CareTakerId作为主键;和一张Animal表,其中CareTakerId为FK。给我一份看护人的名单,我要每个看护人负责的所有动物。大概是这样的: select CareTakerId, count(1) from Animal where CareTakerId in (1,2,3,4) and AnimalTypeId = 3 group by CareTake

我在两个表之间有一个FK关系,但为了进行此查询,我需要获取每个FK的行数

例如,我有一个
CareTaker
表,其中
CareTakerId
作为主键;和一张
Animal
表,其中
CareTakerId
为FK。给我一份看护人的名单,我要每个看护人负责的所有动物。大概是这样的:

select CareTakerId, count(1) 
from Animal
where CareTakerId in (1,2,3,4)
    and AnimalTypeId = 3
group by CareTakerId
返回

CareTakerId | No ColumnName
1           | 42
2           | 6
如何在EntityFramework中实现这一点? 我需要这个结果,所以我想我应该作为一个
字典
字典
)-但是我不知道如何为它编写EF查询。。以下是我目前掌握的情况:

query
    .Where(r => r.AnimalTypeId == animalTypeId 
             && careTakerIds.Contains(r => r.CareTakerId))
    .GroupBy(r => r.CareTakerId)
    // Not sure what to write here; r.CareTakerId doesn't exist
    .Select(r => new {r.key, r.value }) 
    .ToDictionary(kvp => kvp.Key, kvp => kvp.value);

如何在实体框架中选择
CareTakerId
和计数(1)

非常接近,只需添加“Count()”方法即可


选择中执行此操作:

//...
//You have groups here, 
//so you can call Count extension method to get how many elements belong to the current group
.Select(g => new {CareTakerId=g.Key,Count= g.Count() })
.ToDictionary(e=> e.CareTakerId,e=> e.Count);
//...
//You have groups here, 
//so you can call Count extension method to get how many elements belong to the current group
.Select(g => new {CareTakerId=g.Key,Count= g.Count() })
.ToDictionary(e=> e.CareTakerId,e=> e.Count);