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?
Productsyet repeatedly setting the values ofProductSizeorProductInLoopand ignoring the loop variableProduct?Productsin your loop? You want to update the existing ones, right?ProductSize, I'm actually updatingProductSize, instead ofProduct, but I removed all unrelated code trying to simplify/focus on the problem, but I forgot to change it.