Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search other field than id

I'm following and implementing a side project from: https://learn.microsoft.com/es-mx/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.0&tabs=visual-studio

But in the part where [HttpGet("{id}")] is invoked, it works only with the id field, but I want to retrieve a JSON stored in the DBmemory, with other field instead of id; in this case I want to manage data by field TAG. How can I accomplish this?

I've try to change all the id parts to TAG, which is the field I'm looking for, but when I do this, the post method breaks up.

// GET: api/Maquinas/5
[HttpGet("{id}")]                                                                       
public async Task<ActionResult<Maquina>> GetMaquina(string id)
{
  // HERE. i need to find data with the field of "TAG" not "id"
  var maquina = await _context.Maquinas.FindAsync(id);
  if (maquina == null)
  {
    return NotFound();
  }                    
  return maquina;
}
like image 534
Sergio Villalobos Avatar asked Nov 17 '25 02:11

Sergio Villalobos


1 Answers

Don't get stuck on the fact that is called id. You could make use of this endpoint and instead of passing the value of id to pass the value of tag, api/Maquinas/tagvalue.

Later on you should use this value in the call you make to retrieve the entity you are looking for.

_context.Maquinas.FirstOrDefaultAsync(maquina => maquina.Tag == id);

I have assumed here that the property on which you want to filter is called Tag and it's type is string. It is quite probable, at least the name of the property to not be this one. So you have to change the above code correspondingly.

This will fix your problem, but you should not consider this a best practice. The semantics of your API would be broken. The very reason, I shared the above, is to show you that the name of the parameter id is irrelevant with that you pass. There isn't any check that would halt you for passing there "anything". The reason I wrote that the semantics of your API would be broken is that since this is going to be a REST api, someone would expect an endpoint like the following one:

api/Maquinas/1

for getting the entity with id 1.

like image 171
Christos Avatar answered Nov 19 '25 16:11

Christos