Updating Records with Entity Framework 6
This article addresses the challenge of updating records using Entity Framework 6. The provided code retrieves the record to be updated and attempts to attach it to the context before setting its state to Modified and saving the changes. However, an error is encountered indicating that an unexpected number of rows were affected.
The Solution
The error suggests that the record you're trying to update may have been modified since you retrieved it. To resolve this, you should retrieve the object directly from the database context and then make the necessary changes before saving.
Here's a revised version of the code:
using (var db = new MyContextDB()) { var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber); if (result != null) { result.BookName = _book.BookName;
The above is the detailed content of Why Does Updating Records with Entity Framework 6 Sometimes Result in 'Unexpected Number of Rows Affected'?. For more information, please follow other related articles on the PHP Chinese website!