Home > Backend Development > C++ > Why Does Updating Records with Entity Framework 6 Sometimes Result in 'Unexpected Number of Rows Affected'?

Why Does Updating Records with Entity Framework 6 Sometimes Result in 'Unexpected Number of Rows Affected'?

Barbara Streisand
Release: 2025-01-07 08:26:40
Original
604 people have browsed it

Why Does Updating Records with Entity Framework 6 Sometimes Result in

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

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!

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