Returning Task<T> from async method without awaiting

Viewed 336

I have an async method which fetches some data from a DB using Entity Framework via an async call and just want to return that:

public async Task<List<Message>> GetMessagesAsync(string id)
{
   var user = await _dbContext.Users.Where(u.Id == id).AnyAsync();
   if (!user) 
      throw new ApplicationException();
   return  _dbContext.Messages.Where(m => m.Id == id).ToListAsync();
}

The DB query returns a Task to the desired result and I just want to return it without awaiting it here in this method. But the compiler does not allow that, giving me an error message saying

  [CS0266] Cannot implicitly convert type System.Threading.Tasks.Task<System.Collections.Generic.List<Message>>' to 'System.Collections.Generic.List<Message>'. An explicit conversion exists (are you missing a cast?)

If I await the Db query in the last line, the code compiles just fine.

return await _dbContext.Messages.Where(m => m.Id == id).ToListAsync();

I do not understand, why it it necessary to do the await step here instead of doing it in the calling function lateron, when the data is actually needed.

0 Answers
Related