Unable to edit db entries using EFCore, EntityState.Modified: “Database operation expected to affect 1 row(s) but actually affected 0 row(s).”

Unless there is a hidden exception that is hiding behind this as a dumb random exception, the reason is clearly stated in the exception.

Check the Id on the role object as you receive it on your Edit action and try to lookup that id in the database. The exception message you see states that, it is expecting to find a row with a matching Id of the object you attached, but it is not, so it is failing to do the update, since it could not locate a matching row to update it.

EDIT :

You are attaching the entity twice, remove the call to .Attach(role) and keep the line below it which is sufficient to add the object to the tracking context in a modified state.

//_db.Roles.Attach(role); //REMOVE THIS LINE !.
_db.Entry(role).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

Beware that setting the state of the entry to modified will update all the property values upon calling .SaveChanges(), so in case you want to update only certain properties refer to this answer.

If this doesn’t solve your problem, please check for any inner exceptions that you might’ve missed. Sometimes the exception messages don’t make sense and mask the real problem which you might be able to find in the inner exception.

Leave a Comment