无法将 Task<List<TEntity>> 转换为 Task<IList<TEntity>>。

3

我正在编写一个小的封装方法来处理 EF Core 的 DbSet。我有以下方法:

public Task<IList<TEntity>> GetAsync(Func<IQueryable<TEntity>, IQueryable<TEntity>> getFunction)
{
    if (getFunction == null)
    {
        Task.FromResult(new List<TEntity>());
    }
    return getFunction(_dbSet).AsNoTracking().ToListAsync();
}

如您所见,这个类是泛型的,而_dbSet是来自上下文的具体DbSet实例。然而,对于问题并不重要。
对于代码,我得到以下错误:

[CS0029] 无法隐式地将类型 'System.Threading.Tasks.Task>' 转换为 'System.Threading.Tasks.Task<System.Collections.Generic.List<TEntity>>'

如果我将返回值更改为Task<List<TEntity>>,则没有错误。
有人知道为什么它不能进行转换吗?谢谢!


2
可能是异步编程中的类型转换错误的重复问题。 - Owen Pauling
@Sinatr 你可以提出修改意见,我很乐意接受 :) 无论如何感谢你。 - Vitalii Isaenko
4
Task不是一个接口,因此不支持协变Task<List<...>> 只能生成 List<...> 而不能生成实现 IList<...> 接口的任何类。虽然这样做可能是有用的,但并没有被认为足够有用以实际实现。 - Jeroen Mostert
1个回答

5
在我看来,最简单的方法是等待任务。这样可以以最少的更改来完成:
public async Task<IList<TEntity>> GetAsync(Func<IQueryable<TEntity>, IQueryable<TEntity>> 
getFunction)
{
    if (getFunction == null)
    {
        return new List<TEntity>();
    }
    return await getFunction(_dbSet).AsNoTracking().ToListAsync();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接