【问题标题】:.NET / EF: How do I get around the 'ambiguity problem' to create a query with a group by?.NET / EF:如何解决“歧义问题”来创建带有分组依据的查询?
【发布时间】:2021-03-11 18:57:18
【问题描述】:

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

以下方法或属性之间的调用不明确:'System.Linq.Queryable.GroupBy(System.Linq.IQueryable, System.Linq.Expressions.Expression >)' 和 'System.Linq.AsyncEnumerable.GroupBy(System.Collections.Generic.IAsyncEnumerable, System.Func)

此错误与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(),因为它会在执行分组之前检索所有记录。

【问题讨论】:

  • 抱歉,我正在运行 EF 核心版本 6.0.0-preview.2.21154.2 试图解决这个问题,但我错误地将这个问题标记为标准 EF 6。
  • 为此添加了相应的(新)标签

标签: c# .net-core ef-core-6-preview


【解决方案1】:

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

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

Note this will not be an issue in EFCore 6

【讨论】:

  • 谢谢,.AsQueryable() 和 .AsAsyncEnumerable() 解决了这个问题。虽然我尝试运行 EF Core 6 的预览版,但不幸的是它仍然存在。希望它会在完整版本发布时得到解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多