当在DbSet< T>上使用LINQ扩展方法时,模棱两可的调用。 [英] Ambiguous call when using LINQ extension method on DbSet<T>

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

问题描述

我在 DbSet< T> 上使用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引起的。异步包以及 DbSet< TEntity> 类。

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

DbSet< TEntity> 同时实现 IQueryable< TEntity> IAsyncEnumerable< TEntity> ,导入名称空间 System.Linq Microsoft.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 to import 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< TEntity>

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天全站免登陆