0

I am designing an API endpoint and planning to send the response with 2 values ( one with total no of records and second with list of records ) The controller action is designed like below

    [HttpGet]
    [Route("users_bycat")]
    public async Task<ActionResult> GetUsersByCat([FromQuery] int categoryId )
    {       
        var query = db_context.Users.Select(a => a).Where(p => p.CategoryId == categoryId);                   
        var result = await query.ExecuteAsync();

        return Ok(
               new
               {
                   totalRecords = result.Count(),
                   users = result.ToList()
               }
            );
    }

When i am calling this api endpoint, i am getting response like below

    {
        "totalRecords": 37652,
        "users": []
    }

The users array is empty and i try like below , and managed to get the list as response , but i would like to add count as well to the response

    return Ok(  result.ToList());

How can i ensure i will get both totalRecords and users List as a part of response

1
  • You don't need to call query.ExecuteAsync() as query.ToList() will fetch the result, in fact, you can remove the .Select(a => a) also. Commented May 19, 2021 at 11:03

1 Answer 1

4

The ExecuteAsync() is redundant as an IQueryable is materialised upon calling .ToList(). Additionally, calling .Count() will execute an additional database query so it's more efficient to move this call onto the List. The exception to this would be if you were implementing paging.

The below should function as required:

[HttpGet]
[Route("users_bycat")]
public async Task<ActionResult> GetUsersByCat([FromQuery] int categoryId )
{       
    var results = await db_context.Users
      .Where(p => p.CategoryId == categoryId)
      .ToListAsync();
    
    var dto = new
    {
      totalRecords = results.Count,
      users = results
    };

    return Ok(dto);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.