jcthom114
jcthom114

Reputation: 1

Sorting ID in a database

I have a built out an API web app with ASP.NET Core/EF. I have all my models, controllers, and interfaces created and I am able to make GET, POST, PUT, and DELETE calls. However, when I do a GET call in any of my controllers....the IDs don't return in numerical order. For example, the Category controller looks like this:

enter image description here

Where/How can I check for logs or information on why this happened. How can I implement a sort method to solve this?

I can successfully call all my API endpoints and do the functionality for GET, POST, PUT, DELETE, but my IDs aren't correct. Each controller (Pokemon, Category, Owner,etc) the IDs are in numerical order, but they do not start at one.

GET Code

public IActionResult GetCategories() 
{ 
      var categories = _mapper.Map<List<CategoryDto>>
                        (_categoryRepository.GetCategories()); 
      if (!ModelState.IsValid) 
          return BadRequest(ModelState); 
      return Ok(categories); 
} 

Upvotes: 0

Views: 108

Answers (1)

Steve
Steve

Reputation: 216243

As I have told you in the comment above, you should sort your result before returning it to the View. This is the whole concept behing MVC patterns, you do your work in the controller to prepare the result and send it to the View who just display it

public IActionResult GetCategories() 
{ 
    if (!ModelState.IsValid) 
        return BadRequest(ModelState); 

    var data = _categoryRepository.GetCategories().OrderBy(x => x.Id);
    var categories = _mapper.Map<List<CategoryDto>>(data); 
    return Ok(categories); 
} 

As you can see I have also moved the check for the ModelState before starting any work on the database. A proper try/catch handler should also be considered to be on the safe side if anything database or mapping related goes wrong.

Upvotes: 1

Related Questions