gpt4 book ai didi

c# - 在 DbSet 上使用 LINQ 扩展方法时出现不明确的调用

转载 作者:行者123 更新时间:2023-12-02 01:19:44 25 4
gpt4 key购买 nike

我正在 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> 一起打包类。

DbSet<TEntity>实现 IQueryable<TEntity>IAsyncEnumerable<TEntity> ,导入命名空间System.LinqMicrosoft.EntityFrameworkCore导致冲突的扩展方法的定义。不幸的是,避免导入其中之一通常是不切实际的。

此行为从 EF.Core 3.0 开始出现,并在 this issue 中进行了讨论。 .

为了解决这个问题,EF.Core 3.1 添加了两个辅助函数 AsAsyncEnumerable()AsQueryable() ,它显式返回相应的接口(interface) IAsyncEnumerable<TEntity>IQueryable<TEntity> .

通过调用所需的消歧函数来修复给定的代码示例:

await _dbContext.Users.AsQueryable().AnyAsync(u => u.Name == name);

await _dbContext.Users.AsAsyncEnumerable().AnyAsync(u => u.Name == name);

关于c# - 在 DbSet<T> 上使用 LINQ 扩展方法时出现不明确的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60347952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com