idetodospoca
idetodospoca

Reputation: 93

Find specific item on icollection

I'm working on an web api and trying to find a product by it's name with icollection, specifically a product that would match the name given (?name={name}).

Currently I have this:

[HttpGet("name", Name = "GetProductByName")]
public ActionResult<Product> GetByName(string _name)
{
    var prod = (from x in _context.Products 
                where x.Name == _name 
                select x).FirstOrDefault();

    if (prod == null)
    {
        return NotFound();
    }
    return prod;
}

But whenever I query the api (api/product/?name={name} I get all results

What am I doing wrong?

EDIT: Remainder of the controller since it's not a parameter mismatch. I am using an EF DbSet

[Route("api/Product")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly OrderingProductsContext _context;

    public ProductController(OrderingProductsContext context)
    {
        _context = context;
    }


    [HttpGet]
    public ActionResult<List<Product>> GetAll()
    {
        return _context.Products.ToList();
    }


    [HttpGet("{id}", Name = "GetProduct")]
    public ActionResult<Product> GetById(long id)
    {
        var prod = _context.Products.Find(id);
        if (prod == null)
        {
            return NotFound();
        }
        return prod;
    }


    [HttpPost]
    public IActionResult Create(Product prod)
    {
        _context.Products.Add(prod);
        _context.SaveChanges();

        return CreatedAtRoute("GetProduct", new { id = prod.ID }, prod);
    }

Upvotes: 1

Views: 2209

Answers (3)

ilkerkaran
ilkerkaran

Reputation: 4354

First, you should use curly brackets in your attribute parameter;

[HttpGet("{name}", Name = "GetProductByName")]

Then you can call that endpoint with this;

 api/product/GetProductByName/{name}

Or if you want to call with query strings you can go with;

[HttpGet(Name = "GetProductByName")]
public ActionResult<Product> GetByName([FromQuery]string name)

and request like ;

api/product/GetProductByName?name={name}

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34170

You are getting _name as parameter but checking your condition with name

change

var prod = (from x in _context.Products where x.Name == name select x).FirstOrDefault();

with

var prod = (from x in _context.Products where x.Name == _name select x).FirstOrDefault();

Upvotes: 2

Christos
Christos

Reputation: 53958

You should replace _name with name in your method definition. Based on the code you have posted is clear that the where clause doesn't make use of the parameter passed at each call of GetByName but the value of variable name is used.

Upvotes: 1

Related Questions