How to Update/Edit multiple records using Entity Framework in ASP.NET MVC

asp.net-mvc c# entity-framework

Question

This is the extent of my ability to update several records.

I started with this.

foreach (var Product in Products)
{
     Product.Price = Price;

     db.Entry(Product).State = EntityState.Modified;
     db.SaveChanges();
 }

But I'm experiencing this issue.

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

I then discovered this solution, which advised me to create a new instance for each loop, but I still experienced the same issue. Here's my effort:

foreach (var Product in Products)
{
     var ProductInLoop = new Product();
     ProductInLoop.Price = Product.Price;

     db.Entry(ProductInLoop).State = EntityState.Modified;
     db.SaveChanges();
 }

I also can't do it this way.db.Entry(Products).State = EntityState.Modified; outside the circle, asEntry() anticipates a single thing.

What can I do to fix this?

1
1
5/23/2017 12:09:35 PM

Accepted Answer

ZZZ_tmp
3
9/10/2015 12:47:17 PM

Popular Answer

It is unnecessary to make a new Product object. Your Products collection is probably already connected to the database context because you are altering records; if you make changes to it, its current state will be recorded.

Do this:

foreach (var Product in Products)
{        
     Product.price = ProductSize.price;
     db.SaveChanges();
}

Add the following line before saving if the Products are not already connected to the context (db):

db.Products.Attach(Product); 

In accordance with convention, you should also update Prodcut in your looping variable to Prodcut: product



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow