Ambiguous call when using LINQ extension method on DbSet<T>

被刻印的时光 ゝ 提交于 2020-12-30 05:13:27

问题


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>>)'

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

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


回答1:


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

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.

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

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);

or

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


来源:https://stackoverflow.com/questions/60347952/ambiguous-call-when-using-linq-extension-method-on-dbsett

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!