我想在序言中说,我对 EF Core 非常陌生,并且已经看过有关此主题的otherfewquestions,但我不明白如何解决我的问题。
我有一个模型
Attempt
:
public class Attempt(int Id, string UserId, int score)
{
public int Id { get; set; } = Id;
public string UserId { get; set; } = UserId!;
public int score { get; set; } = score;
}
我正在尝试执行此查询,该查询按 UserId 对所有尝试进行分组,选择每个用户得分最高的尝试,然后按分数对它们进行排序:
IQueryable<Attempt> GetBestAttempts() =>
db.Attempt
.GroupBy(a => a.UserId)
.Select(g => g.OrderByDescending(attempt => attempt.score).First())
.OrderByDescending(attempt => attempt.score)
.ThenBy(attempt => attempt.UserId);
但是,当尝试实例化此查询时,我收到此错误:
System.Collections.Generic.KeyNotFoundException: 'The given key 'EmptyProjectionMember' was not present in the dictionary.'
有人有不需要实例化查询的解决方案吗?此查询是许多其他查询的一部分,如果可能的话,我希望避免将这个巨大的列表实例化到服务器。
设法通过原始查询解决此问题,感谢 Microsoft 副驾驶...
IQueryable<Attempt> GetBestAttempts() =>
Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSqlRaw(db.Attempt, @"
SELECT a.*
FROM ""Attempt"" a
INNER JOIN (
SELECT ""UserId"", MAX(""score"") AS ""MaxScore""
FROM ""Attempt""
GROUP BY ""UserId""
) maxAttempts ON a.""UserId"" = maxAttempts.""UserId"" AND a.""score"" = maxAttempts.""MaxScore""
WHERE a.""Id"" = (
SELECT MIN(innerA.""Id"")
FROM ""Attempt"" innerA
WHERE innerA.""UserId"" = a.""UserId"" AND innerA.""score"" = a.""score""
)
ORDER BY a.""score"" DESC, a.""UserId"";
");
尽管我讨厌原始 SQL 查询,但现在就这样了。
(我直接调用了扩展方法,因为我的项目中也使用了Linq2Db,想避免名称冲突)