0

I am new to stackoverflow. I would like to know how can I add and Edit products

for example

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

any advice. I have done google and found many example that add or edit product as single object but not as collection

Regards

Isparia
  • 682
  • 5
  • 20
  • Take a look at this link https://stackoverflow.com/questions/43531602/bulk-update-in-entity-framework-core – osman Rahimi Dec 17 '21 at 18:53
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Dec 24 '21 at 01:02

1 Answers1

0

You can do something like this (bear in mind this is just for giving you an idea, no doubt there is a better way)

    [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.

osman Rahimi
  • 1,427
  • 1
  • 11
  • 26