Fix EF6 Inserts Instead of Updates for Existing MVC Records
Editing an existing record inserts a new row or fails on an unexpected duplicate key.
Applies to ASP.NET MVC 5 on .NET Framework. Use a staging or development copy to reproduce the behavior and inspect the actual response before changing production.
Diagnostic flowchart
Isolate the cause
Does the code call DbSet.Add for the edit?
- Yes. Add marks the entity for insertion. The edit endpoint must locate the existing authorized row and change it.
- No. A missing key, relationship mapping or incorrectly marked dependent can introduce an Added entity even without a direct Add call here.
Apply the fix
Use the route ID to load the existing entity in this request’s context and apply validated values. Check that related records are resolved independently before attaching new objects.
var item = db.Items.Find(id);
if (item == null) return HttpNotFound();
item.DisplayName = input.DisplayName;
db.SaveChanges();Verify the result
- Expected path. Verify one row exists before and after a normal update and the selected field changes.
- Regression check. Try an unknown key and confirm the action returns its expected missing-resource result without inserting anything.
Microsoft reference for ef6 persistence · ASP.NET PB Tutorial Index
Comments
Post a Comment