[Solved] IQueryable does not contain definition for GetAwaiter

I’m using WebAPI in entity framework to create a new endpoint and I am having some issues. I’m trying to use a Linq Where statement to get my data, but I’m receiving the following error.

‘IQueryable’ does not contain a definition for ‘GetAwaiter’ and
no extension method ‘GetAwaiter’ accepting a first argument of type
‘IQueryable’ could be found (are you missing a using directive
or an assembly reference?)

Here is my code.

    [ResponseType(typeof(Vocab))]
    public async Task<IHttpActionResult> GetVocabByLesson(int lessonId)
    {
        Vocab vocab = await db.Vocabs.Where(a => a.LessonId == lessonId);
        if (vocab == null)
            return NotFound();

        return Ok(vocab);
    }
Enquirer: nos9

||

Solution #1:

Use FirstOrDefaultAsync extension method:

[ResponseType(typeof(Vocab))]
public async Task<IHttpActionResult> GetVocabByLesson(int lessonId)
{
        Vocab vocab = await db.Vocabs.FirstOrDefaultAsync(a => a.LessonId == lessonId);
        if (vocab == null)
            return NotFound();

        return Ok(vocab);
}

By your code I can deduct you want to return just an element, that’s why I have suggested to use FirstOrDefaultAsync. But in case you want to get more than one element that meets some condition then use ToListAsync:

[ResponseType(typeof(Vocab))]
public async Task<IHttpActionResult> GetVocabByLesson(int lessonId)
{
        var result= await db.Vocabs.Where(a => a.LessonId == lessonId).ToListAsync();
        if (!result.Any())
            return NotFound();

        return Ok(result);
}
Respondent: octavioccl

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.