GroupBy 无法翻译

joh*_*y 5 5 c# linq-to-entities group-by entity-framework-core .net-core

我正在尝试从数据库中删除重复项。我正在使用 Entity Framework Core 和 .NET 5。EF Core 在具体化我的组时遇到了困难:

protected async Task RemoveDuplicates(CryptoInfoContext cryptoContext)
{
    try
    {
        var duplicates = cryptoContext.HistoricalCandles
            .GroupBy(x => new { x.StartDate, x.GranularitySeconds })
            .Where(x => x.Count() > 1)
            .ToList()
            .Select(x => x.FirstOrDefault())
            .ToList();

        cryptoContext.RemoveRange(duplicates);
        await cryptoContext.SaveChangesAsync();
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

无法翻译给定的“GroupBy”模式。在“GroupBy”之前调用“AsEnumerable”以在客户端对其进行评估

我不想具体化所有行来删除重复项。是否有 group by 的已知问题列表?我该如何解决这个问题?

joh*_*y 5 4

感谢@GertArnold 为我指明了正确的方向。显然 EF Group by 只支持聚合查询。

正如这篇文章所指出的:

var ctx = new EntertainmentDbContext(conString);

var dataTask = ctx
            .Ratings
            .GroupBy(x => x.Source)
            .Select(x => new {Source = x.Key, Count = x.Count()})
            .OrderByDescending(x => x.Count)
            .ToListAsync();

var data = await dataTask;
Run Code Online (Sandbox Code Playgroud)

这将生成如下 SQL:

SELECT "r"."Source", COUNT(*) AS "Count"
FROM "Ratings" AS "r"
GROUP BY "r"."Source"
ORDER BY COUNT(*) DESC
Run Code Online (Sandbox Code Playgroud)

注意:目前几乎没有其他方法可以工作,你甚至不能在 group by 之前应用 where 。

此外,还有一个开放的EF Core 问题, 请对其进行投票,以便他们真正修复此问题,而不是推送另一个版本