我正在使用最新版本的 .NET Core (.NET 5) 和 Entity Framework Core 6(预览版)连接到 MySQL 数据库。我正在尝试使用 GroupBy 通过查询生成组以在数据库服务器上执行,如此处所述。不幸的是,这无法编译并出现错误
以下方法或属性之间的调用不明确:'System.Linq.Queryable.GroupBy<TSource, TKey>(System.Linq.IQueryable, System.Linq.Expressions.Expression<System.Func<TSource, TKey>>)'和 'System.Linq.AsyncEnumerable.GroupBy<TSource, TKey>(System.Collections.Generic.IAsyncEnumerable, System.Func<TSource, TKey>)
此错误与 LINQ 和 EF Core 共享相同的方法有关,此处详细讨论。我已经尝试了为每个 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() 因为这会在执行分组之前检索所有记录。