在icollection上查找特定项目

时间:2018-10-05 10:53:38

标签: c# asp.net linq icollection

我正在开发一个Web api,并尝试使用icollection以其名称查找产品,特别是一种与给定名称(?name = {name})匹配的产品。

目前我有这个:

[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;
}

但是每当我查询api(api / product /?name = {name}时,我都会得到所有结果

我在做什么错了?

编辑:控制器的其余部分,因为它不是参数不匹配。我正在使用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);
    }

3 个答案:

答案 0 :(得分:1)

您应该在方法定义中将_name替换为name。根据您已发布的代码,很明显where子句没有利用在每次GetByName调用时传递的参数,而是使用了变量name的值。

答案 1 :(得分:1)

您将_name作为参数,但使用name检查您的状况

更改

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

使用

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

答案 2 :(得分:0)

首先,您应该在属性参数中使用大括号;

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

然后您可以使用该名称调用该端点;

 api/product/GetProductByName/{name}

或者,如果您要使用查询字符串进行调用,可以使用;

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

并要求类似;

api/product/GetProductByName?name={name}