我需要更新多条记录,这是我能做到的程度
首先,我试过这个
foreach (var Product in Products)
{
Product.Price = Price;
db.Entry(Product).State = EntityState.Modified;
db.SaveChanges();
}
但是,我收到了这个错误
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.
然后,我找到了this回答,说我应该为每次迭代创建新实例,但我得到了同样的错误。以下是我的尝试。
foreach (var Product in Products)
{
var ProductInLoop = new Product();
ProductInLoop.Price = Product.Price;
db.Entry(ProductInLoop).State = EntityState.Modified;
db.SaveChanges();
}
我也不能在循环外像这样 db.Entry(Products).State = EntityState.Modified; 这样做,因为 Entry() 需要一个 singel对象。
我该如何解决这个问题?
请您参考如下方法:
感谢 Ben Robinson 的评论,我解决了这个问题。造成这个问题的原因是我没有将主键从View传递给Controller。
在 View 中,我添加了这个隐藏字段来传递 primary key,如下所示:
<input type="hidden" name="[@i].id" value="@Product.id" />
服务器端代码是这样的
foreach (var product in Products)
{
product.Price = Price;
db.Entry(product).State = EntityState.Modified;
}
db.SaveChanges();
