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

asp.net-mvc c# entity-framework

Question

I need to update multiple records, this is how far I could get

First, I tried this

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

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

But, I'm getting this error

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.

Then, I found this answer, saying that I should create new instance for each iteration, but I got the same error. Below is my attempt.

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

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

Also I can't do it like this db.Entry(Products).State = EntityState.Modified; outside the loop, because Entry() expects a singel object.

How can I solve this?

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

Accepted Answer

Thanks to Ben Robinson's comment, I solved this. The problem caused because I didn't pass the primary key from View to Controller.

In View I added this hidden field to pass the primary keys like this:

<input type="hidden" name="[@i].id" value="@Product.id" />

and server side code look like this

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

    db.Entry(product).State = EntityState.Modified;
 }
 db.SaveChanges();
3
9/10/2015 12:47:17 PM

Popular Answer

There is no need to create a new Product object. Since you are modifying records, your Products collection is likely already attached to the database context, and it's state will be tracked if you modify it.

Try this:

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

if the Products are not attached to the context (db), add this line before saving:

db.Products.Attach(Product); 

by convention, you should also change your looping variable from Prodcut to the lowercase form : 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