【问题标题】:Http post and put as IEnumerableHttp 发布并作为 IEnumerable
【发布时间】:2022-01-20 08:03:16
【问题描述】:

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

例如

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

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

问候

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: asp.net asp.net-core webapi


【解决方案1】:

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

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

不要在每个循环中调用 SaveChanges()。

【讨论】:

  • 您好,感谢您的回复。我想知道这样做的最佳方法是什么。
  • 你忘了做 _dbContext.Products.Update(productInDb);在 foreach 循环内
  • @GeorgeHarris 不需要,Change Tracker 知道哪条记录发生了变化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-26
  • 2014-06-22
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多