在 DbSet<T> 上使用 LINQ 扩展方法时调用不明确
Ambiguous call when using LINQ extension method on DbSet<T>
我正在 DbSet<T>
:
上使用 LINQ 查询
await _dbContext.Users.AnyAsync(u => u.Name == name);
但是,编译器输出以下错误:
Error CS0121: The call is ambiguous between the following methods or properties:
'System.Linq.AsyncEnumerable.AnyAsync<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Func<TSource, bool>)' and
'Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource, bool>>)'
其他 LINQ 扩展方法也会出现类似的问题,例如 .Where()
。
我正在使用 EF.Core 3.1 并安装了 System.Linq.Async
软件包。我该如何解决这个问题?
所描述的问题是由 System.Linq.Async
软件包与 DbSet<TEntity>
class.
软件包一起使用引起的
由于 DbSet<TEntity>
同时实现了 IQueryable<TEntity>
和 IAsyncEnumerable<TEntity>
,因此导入命名空间 System.Linq
和 Microsoft.EntityFrameworkCore
会导致定义冲突的扩展方法。不幸的是,避免导入其中之一通常是不切实际的。
此行为从 EF.Core 3.0 开始存在,并在 this issue.
中进行了讨论
为了解决这个问题,EF.Core 3.1 增加了两个辅助函数 AsAsyncEnumerable()
和 AsQueryable()
,明确 return 各自的接口 IAsyncEnumerable<TEntity>
或 IQueryable<TEntity>
.
通过调用所需的消歧函数修复给定的代码示例:
await _dbContext.Users.AsQueryable().AnyAsync(u => u.Name == name);
或
await _dbContext.Users.AsAsyncEnumerable().AnyAsync(u => u.Name == name);
我正在 DbSet<T>
:
await _dbContext.Users.AnyAsync(u => u.Name == name);
但是,编译器输出以下错误:
Error CS0121: The call is ambiguous between the following methods or properties:
'System.Linq.AsyncEnumerable.AnyAsync<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Func<TSource, bool>)' and
'Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource, bool>>)'
其他 LINQ 扩展方法也会出现类似的问题,例如 .Where()
。
我正在使用 EF.Core 3.1 并安装了 System.Linq.Async
软件包。我该如何解决这个问题?
所描述的问题是由 System.Linq.Async
软件包与 DbSet<TEntity>
class.
由于 DbSet<TEntity>
同时实现了 IQueryable<TEntity>
和 IAsyncEnumerable<TEntity>
,因此导入命名空间 System.Linq
和 Microsoft.EntityFrameworkCore
会导致定义冲突的扩展方法。不幸的是,避免导入其中之一通常是不切实际的。
此行为从 EF.Core 3.0 开始存在,并在 this issue.
中进行了讨论为了解决这个问题,EF.Core 3.1 增加了两个辅助函数 AsAsyncEnumerable()
和 AsQueryable()
,明确 return 各自的接口 IAsyncEnumerable<TEntity>
或 IQueryable<TEntity>
.
通过调用所需的消歧函数修复给定的代码示例:
await _dbContext.Users.AsQueryable().AnyAsync(u => u.Name == name);
或
await _dbContext.Users.AsAsyncEnumerable().AnyAsync(u => u.Name == name);