3

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!

Vitalii Isaenko
  • 941
  • 1
  • 14
  • 37
  • 2
    Possible duplicate of [Type conversion error with async programming](https://stackoverflow.com/questions/20950908/type-conversion-error-with-async-programming) – Owen Pauling Jun 06 '19 at 12:32
  • @Sinatr You could propose edit and I would be glad to accept it :) Thank you anyway – Vitalii Isaenko Jun 06 '19 at 12:33
  • 4
    `Task` is not an interface and hence [doesn't support covariance](https://stackoverflow.com/q/2733346/4137916). A `Task>` can only yield a `List<...>` and not any class implementing `IList<...>`. It would conceivably be useful to do so, but isn't considered useful enough to actually implement. – Jeroen Mostert Jun 06 '19 at 12:34

1 Answers1

5

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();
}
Ivan Chepikov
  • 795
  • 4
  • 22