在 DbSet<T> 上使用 LINQ 扩展方法时的不明确调用 [英] Ambiguous call when using LINQ extension method on DbSet<T>

查看:14
本文介绍了在 DbSet<T> 上使用 LINQ 扩展方法时的不明确调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 DbSet 上使用 LINQ 查询:

I am using a LINQ query on a DbSet<T>:

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

但是编译器输出如下错误:

However, the compiler outputs the following error:

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().

A similar problem also occurs with other LINQ extension methods, like .Where().

我正在使用 EF.Core 3.1 并安装了 System.Linq.Async 包.我该如何解决这个问题?

I am using EF.Core 3.1 and have the System.Linq.Async package installed. How do I fix this issue?

推荐答案

所描述的问题是由使用 System.Linq.Async 包和 DbSet 包引起的代码>类.

The described problem is caused by using the System.Linq.Async package along with the DbSet<TEntity> class.

由于 DbSet 实现了 IQueryableIAsyncEnumerable,导入命名空间 System.LinqMicrosoft.EntityFrameworkCore 导致定义冲突的扩展方法.不幸的是,避免导入其中之一通常是不切实际的.

Since DbSet<TEntity> implements both IQueryable<TEntity> and IAsyncEnumerable<TEntity>, importing the namespaces System.Linq and Microsoft.EntityFrameworkCore leads to the definition of the conflicting extension methods. Unfortunately, avoiding importing one of them is usually not practicable.

此行为从 EF.Core 3.0 开始就存在,并在 这个问题.

This behavior is present beginning with EF.Core 3.0, and is discussed in this issue.

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

In order to address this, EF.Core 3.1 adds two auxiliary functions AsAsyncEnumerable() and AsQueryable(), which explicitly return the respective interfaces IAsyncEnumerable<TEntity> or IQueryable<TEntity>.

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

The given code sample is fixed by calling the desired disambiguation function:

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

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

这篇关于在 DbSet&lt;T&gt; 上使用 LINQ 扩展方法时的不明确调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆