When attempting to update a record using Entity Framework 6, you may encounter the error "Store update, insert, or delete statement affected an unexpected number of rows." This error arises because the record may have been modified or deleted since it was initially loaded into the context.
To resolve this issue, you can use the following approach:
Here's an updated code sample that demonstrates this approach:
using (var db = new MyContextDB()) { var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber); if (result != null) { result.SomeValue = "Some new value"; db.SaveChanges(); } }
This updated code retrieves the record, assigns the new value to the appropriate property, and then saves the changes. By directly modifying the retrieved record, you avoid the need to attach it explicitly or set the entity state, thereby resolving the concurrency exception.
The above is the detailed content of How to Resolve 'Store update, insert, or delete statement affected an unexpected number of rows' in Entity Framework 6?. For more information, please follow other related articles on the PHP Chinese website!