Search code examples
c#asynchronousasync-awaitcovariancecontravariance

Cannot convert Task<List<TEntity>> to Task<IList<TEntity>>


I'm writing a small wrapper method around EF Core DbSet. I have the following method:

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

The class is generic as you can see and _dbSet is an instance of concrete DbSet from the context. It does not matter that much for the question, however.
For the code I get the below error:

[CS0029] Cannot implicitly convert type 'System.Threading.Tasks.Task>' to 'System.Threading.Tasks.Task>'

If I change return value to Task<List<TEntity>> there is no error.
Does anyone have an idea why it cannot convert it? Thanks!


Solution

  • The easiest way in my opinion is to await the task. So it will work with minimum changes:

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