Home > Backend Development > C++ > How to Resolve 'Store update, insert, or delete statement affected an unexpected number of rows' in Entity Framework 6?

How to Resolve 'Store update, insert, or delete statement affected an unexpected number of rows' in Entity Framework 6?

Barbara Streisand
Release: 2025-01-07 08:22:40
Original
714 people have browsed it

How to Resolve

Resolving Concurrency Exception in Entity Framework 6 Record Updates

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:

  1. Retrieve the record from the database using the SingleOrDefault method.
  2. Check if the record exists using the if condition.
  3. Directly modify the retrieved record's properties as needed.
  4. Save the changes to the database using the SaveChanges method.

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();
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template