Linq to SQL 按控制器分组

Linq to SQL Group by Controller

我正在尝试学习如何编写 sql 查询以查询 return 条记录,然后按 ID 将其分组并 return 到列表。我尝试了一些东西,但一直无法将类型 System.Collections.Generic.List<>' 隐式转换为 'System.Linq.IQueryable..etc

到目前为止我在我的存储库中尝试过的内容:

    public IQueryable<CHECKLIST> GetAllComplaintsCount()
    {
        try
        {
            return _context.Checklists
                .GroupBy(a => a.MonitorEnteredEmpID)
                .Select(a => new { Amount = a.Sum(b =>b.MonitorEnteredEmpID), Name = a.Key })
                .ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError("Could not get am with checklist", ex);
            return null;
        }
    }

如果我将其更改为 IEnumerable,则会出现此错误:

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: int Amount, int Name>>' to 'System.Collections.Generic.IEnumerable

问题

有人可以告诉我我做错了什么以及我如何 return EntereredEMPID 对所有清单的计数吗?

您的方法 GetAllComplaintsCount() 的 return 类型是 IQueryable<CHECKLIST>。但是在您的查询中,您在

创建了一个匿名类型
.Select(a => new { Amount = a.Sum(b =>b.MonitorEnteredEmpID), Name = a.Key })

然后您尝试 return 一个 List<T> 这种匿名类型。所以这不能转换成 IQueryable<CHECKLIST>.

所以我猜你有一个名为 CHECKLIST 的 class(或结构),它具有名为 AmountName 的属性(当你在查询中使用它们时) .现在,不是创建匿名类型的实例,而是创建 CHECKLIST:

的实例
 return _context.Checklists
            .GroupBy(a => a.MonitorEnteredEmpID)
            .Select(a => new CHECKLIST { Amount = a.Sum(b =>b.MonitorEnteredEmpID), Name = a.Key });

并根据需要省略 .ToList() return IQueryable 而不是完成的 List.

当然,如果你不想稍后执行查询但是return一个枚举List,你需要将你的方法的签名更改为List<CHECKLIST>并使用.ToList() 像这样:

public List<CHECKLIST> GetAllComplaintsCount()
{
    try
    {
        return _context.Checklists
            .GroupBy(a => a.MonitorEnteredEmpID)
            .Select(a => new CHECKLIST { Amount = a.Sum(b =>b.MonitorEnteredEmpID), Name = a.Key })
            .ToList();
    }
    catch (Exception ex)
    {
        _logger.LogError("Could not get am with checklist", ex);
        return null;
    }
}

更新:

由于您(可能)实际上希望知道具有 MonitorEnteredEmpID 的元素的 计数 ,您可能会考虑完全不同的 return 类型。将 MonitorEnteredEmpID 映射到元素计数的 Dictionary<int, int> 怎么样:

public Dictionary<int, int> GetAllComplaintsCount()
{
    try
    {
        return _context.Checklists
            .GroupBy(a => a.MonitorEnteredEmpID)
            .ToDictionary(g => g.Key, g => g.Count);
    }
    catch (Exception ex)
    {
        _logger.LogError("Could not get am with checklist", ex);
        return null;
    }
}

所以你可以这样使用:

Dictionary<int, int> result = GetAllComplaintsCount();
Console.WriteLine("ID        COUNT");
foreach(int id in result.Keys)
    Console.WriteLine($"{id}        {result[id]}");