-1

I have this in my repository:

public async Task<IEnumerable<CatalogModel>> GetCatalogByName(string _UserId, string _CatalogName)
{
    var data =  await dbcontext.Catalog.Where(x => x.UserId == _UserId).ToListAsync();
    return mapper.Map<IEnumerable<CatalogModel>>(data);
}

And currently, this in my Controller:

[HttpGet]
public IActionResult GetCatalogsByName([FromQuery] string UserId, string CatalogName)
{
     var task = repository.Catalog.GetCatalogByName(UserId, CatalogName);
     return Ok(task);
 }

So right now I am returning Ok(task) all the time. I would like to check if there is data returned from the repository or not so I can also return NotFound(task). I could not seem to figure out how to do that.

1

1 Answer 1

1

You will need to wait for the GetCatalogByName to complete before examining the result.

A simple await will do

[HttpGet]
public IActionResult GetCatalogsByName([FromQuery] string UserId, string CatalogName)
{
     var task = await repository.Catalog.GetCatalogByName(UserId, CatalogName);
     // check task data before return
     return Ok(task);
}

But I strongly recommend you to read more about async/await programming here

3
  • I will read through the links you and @paulsm4 provided. Adding await would change my controller method to public async Task<IActionResult> GetCatalogsByName([FromQuery] string UserId, string CatalogName). I still don't have idea how to check the task if there is a record or not. Feb 3, 2022 at 23:30
  • Changing a signature to Task<IActionResult> won't change the result of a method. When you await the Task you actually "unwrap" Task<> and receive the result of it. In your case, after awaiting, the task type is IEnumerable<CatalogModel>, so, you can work with task as collection using Linq
    – Serhii
    Feb 4, 2022 at 0:16
  • Thank you very much for the inputs. After reading the article in the suggested links, I gained more knowledge and I now understand how it works. Feb 4, 2022 at 1:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.