Failed to edit db entries using EFCore, EntityState.Modified: "The database operation should affect 1 row (s), but it actually affects 0 row (s)."

I am using Identity Core 1.0 with ASP.NET MVC Core 1.0 and Entity Framework Core 1.0 to create a simple user registration system with this article as a starting point, and I'm trying to add user roles. I can add user roles, but I can’t edit them. Here is the Edit action in the RolesController :

  [HttpPost] [ValidateAntiForgeryToken] public IActionResult Edit(IdentityRole role) { try { _db.Roles.Attach(role); _db.Entry(role).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { Console.WriteLine(ex); return View(); } } 

Here is the form in the corresponding view:

 @model Microsoft.AspNet.Identity.EntityFramework.IdentityRole @{ ViewBag.Title = "Edit"; } <h2>Edit Role</h2> <hr /> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) @Html.HiddenFor(model => model.Id) <div>Role name</div> <p>@Html.TextBoxFor(model => model.Name)</p> <input type="submit" value="Save" /> } 

The name of the new role is not stored in the database, and I get the following exception: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.

I was able to use this exact code (with Microsoft.AspNet.Identity.EntityFramework dependency instead of EntityFrameworkCore ) to edit database records using EF 7, Identity 3, etc.

Any thoughts on why this code does not allow changing records in the database?

+13
source share
8 answers

If there is a hidden exception that is hidden behind it as a mute random exception, the reason is clearly indicated in the exception.

Check the Id on the role object when you get it in your Edit action, and try to find that identifier in the database. The exception message that you see indicates that it expects to find a string with the corresponding identifier for the object that you connected, but it is not, therefore, it does not update because it could not find a suitable string to update it.

EDIT:

You attach the object twice, remove the .Attach(role) call and hold the line below it, which is enough to add the object to the tracking context in an altered state.

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

Beware that setting the changed record state will update all property values ​​when you call .SaveChanges() , so if you want to update only certain properties, refer to this answer .

If this does not solve your problem, check for any internal exceptions that you might have missed. Sometimes exception messages are meaningless and mask the real problem that you might find in an internal exception.

+4
source

You can try as shown below.

 [HttpPost] [ValidateAntiForgeryToken] public IActionResult Edit(IdentityRole role) { try { _db.Entry(role).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { Console.WriteLine(ex); return View(); } } 

Note:

When _db.Entry(role).State = EntityState.Modified;

  • you not only attach the object to _db , but also mark the entire dirty object.
  • When you execute _db.SaveChanges() , EF will generate an update that will update all the fields of the entity .

When _db.Roles.Attach(role)

  • binds the object to the context without marking it dirty .
  • This is like _db.Entry(role).State = EntityState.Unchanged; .
  • if you do not go to update a property on the entity , the next time you call context.SaveChanges() EF will not generate a database update for this entity .

ie If you need to create a database update, you need to do the following:

 _db.Roles.Attach(role); // State = Unchanged role.RoleName = "Admin"; // State = Modified, and only the RoleName property is dirty context.SaveChanges(); 
+2
source

Your answers do not work for me. And I solved my mistake as follows. Changed model class proportions

 [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public string Id { get; set; } 

after i changed my display class

 builder.Property(c => c.Id).HasColumnName("ID").IsRequired(); 

Last change

  CustomerEntity thisrole = (from x in db.Customers where x.Id == Id select x).First(); thisrole.Id = accountNum; thisrole.Name = name; thisrole.Phone = phone; thisrole.Email = email; thisrole.Address = address; db.SaveChanges(); return true; 

I hope this solution works for someone.

+1
source

After updating or deleting, EF Core reads the number of rows affected.

 SELECT [ExampleEntityId] FROM [ExampleEntities] WHERE @@ROWCOUNT = 1 AND [ExampleEntityId] = scope_identity(); 

If your entities do not have an IdentityColumn primary key, EF Core throws a DbUpdateConcurrencyException.

In my case, I added primary keys (and set them as an identity) to the linked tables in the database.

+1
source

I solved this by combining the two methods

 var thisRole = _db.Roles.Where(r => r.Id.Equals(role.Id, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); _db.Roles.Attach(thisRole); thisRole.Name = role.Name; _db.SaveChanges(); 
0
source

If the table has an INSTEAD OF INSERT trigger, the database cancels the operation and EntityFramework fires this error.

0
source

The same error here that ended up being the problem I insert by reusing the code for the update ...

  Role role = new Role(); role.Value = input; context.Add(role); await context.SaveChangesAsync(); 

There is no state to be changed upon insertion ...

0
source

mysql requires AUTO_INCREMENT identifier

like this:

ALTER TABLE wfdbcore201test . wftransitioninstance MODIFY COLUMN ID int (11) NOT NULL AUTO_INCREMENT FIRST;

0
source

All Articles