.NET / EF:如何绕过 'ambiguity problem' 来创建带有分组依据的查询?

.NET / EF: How do I get around the 'ambiguity problem' to create a query with a group by?

我正在使用最新版本的 .NET Core (.NET 5) 和 Entity Framework Core 6(预览版)连接到 MySQL 数据库。我正在尝试使用 GroupBy 生成一个分组查询以在数据库服务器上执行,如 here 所述。不幸的是,这无法编译并出现错误

The call is ambiguous between the following methods or properties: 'System.Linq.Queryable.GroupBy<TSource, TKey>(System.Linq.IQueryable, System.Linq.Expressions.Expression<System.Func<TSource, TKey>>)' and 'System.Linq.AsyncEnumerable.GroupBy<TSource, TKey>(System.Collections.Generic.IAsyncEnumerable, System.Func<TSource, TKey>)

此错误与 LINQ 和 EF Core 共享相同的方法有关,详细讨论 here。我已尝试使用以下代码为每个 LINQ 调用创建扩展方法的建议解决方法:

    {
        public static IQueryable<TEntity> Where<TEntity>(this Microsoft.EntityFrameworkCore.DbSet<TEntity> obj, System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            return System.Linq.Queryable.Where(obj, predicate);
        }

        public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(
            this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector, Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector)
        {
            return System.Linq.Queryable.GroupBy(source, keySelector, elementSelector, resultSelector);
        }

        public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector)
        {
            return System.Linq.Queryable.GroupBy(source, keySelector);
        }

    }

这解决了 'Where()' 的问题,但 GroupBy() 的错误仍然存​​在。我应该使用不同的扩展方法来解决这个问题,还是其他一些解决方法?我不能使用 AsEnumerable(),因为它会在执行分组之前检索所有记录。

当不需要 IAsyncEnumerable<T> 时,在 DbSet<T> 上使用 .AsQueryable(),反之亦然,以消除歧义:

dbContext.YourEntities
    .AsQueryable() // or .AsAsyncEnumerable()
    // ...
    .GroupBy(ye => ye.PropertyA);

Note this will not be an issue in EFCore 6