Reputation: 811
I have 6 related tables. I am using a view model to show the properties from all 6 tables in my view. I am able to add data in single transaction using the above structure. But while editing the data I get - "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded." error message.
From the message it seems that the 0 rows were affected in some table. In my view it might be possible that not every value will be edited. Only some values belonging to some table will be edited and some will be stored as it is. So if the values from one table are not at all edited and if I try to do the following, then the above error pops up:
db.Entry(tbl).State = EntityState.Modified;
db.SaveChanges();
Is there a way to Modify the entity state of only those tables whose values are edited in the Edit View? Or is there any other better approach for this?
Upvotes: 1
Views: 1296
Reputation: 475
Example of editing an entity:
//Get the database entry
var entity = db.Person.First(c=>c.ID == 1);
//OR
//Attach a object to the context, see Nsevens answer.
db.Person.Attach(entity);
//Change a property
entity.Job = "Accountant";
//State it's a modified entry
db.Entry(entity).State = EntityState.Modified;
//Save
db.SaveChanges();
If you are editing multiple entries you will need to set every one to EntityState.Modifed
, for example in a foreach
loop.
Upvotes: 2
Reputation: 2835
For a project here we did the following:
Perhaps an important one, is the Context.People.Attach()
method.
Context.People.Attach(person);
// Disable validation otherwise you can't do a partial update
Context.Configuration.ValidateOnSaveEnabled = false;
Context.Entry(person).Property(x => x.AddressId).IsModified = true;
Context.Entry(person).Property(x => x.Birthday).IsModified = true;
Context.Entry(person).Property(x => x.Name).IsModified = true;
...
await Context.SaveChangesAsync();
Perhaps this is something you can work with? Not sure if the same approach can help for your case.
Upvotes: 2