更新时间:2021-12-02 21:30:14
使用 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);
}