Http post 并作为 IEnumerable

Http post and put as IEnumerable

我是 Whosebug 的新手。我想知道如何添加和编辑产品

例如

     [HttpPost("api/products")]
     public ActionResult <IEnumerable<Product>> CreateProducts(IEnumerable<Product> products)
     {
      //    Note: I am getting product as collection
      //    I am using ef core. and would like to add all products
     }
    
    
    [HttpPut("api/products")]
    public ActionResult <IEnumerable<Product>> updateProducts(IEnumerable<Product> products)
    {
    //      Note: I am getting product as collection
    //      I am using ef core. and would like to edit all products
    }

    class  Product
    {
       public int Id {get;set;}
       public string Name {get;set;}
       public string Price {get;set;}
    }

任何建议。我已经完成 google 并发现许多示例将产品添加或编辑为单个对象而不是集合

此致

你可以这样做(记住这只是给你一个想法,毫无疑问还有更好的方法)

    [HttpPut("api/products")]
    public ActionResult <IEnumerable<Product>> updateProducts(IEnumerable<Product> products)
    {
     foreach(var product in products)
      {
         var propuctInDb=_dbContext.Products.SingleOrDefault(x=>x.Id==product.Id);
          productInDb.Name=product.Name;
        productInDb.Price=product.Price;
       }
  _dbContext.SaveChanges();
  }

Do not call SaveChanges() in each loop.