IQueryable不包含GetAwaiter的定义 [英] IQueryable does not contain definition for GetAwaiter

查看:114
本文介绍了IQueryable不包含GetAwaiter的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实体框架中使用WebAPI来创建新的端点,但遇到了一些问题.我正在尝试使用Linq Where语句获取我的数据,但是我收到以下错误.

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"不包含"GetAwaiter"的定义,并且 没有扩展方法'GetAwaiter'接受类型的第一个参数 可以找到"IQueryable"(您是否缺少using指令? 还是程序集引用?)

'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?)

这是我的代码.

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

推荐答案

使用 FirstOrDefaultAsync 扩展方法:

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

通过您的代码,我可以推断出您只想返回一个元素,这就是为什么我建议使用FirstOrDefaultAsync的原因.但是,如果您想获得多个满足某些条件的元素,请使用 ToListAsync :

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

这篇关于IQueryable不包含GetAwaiter的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆