i´m having some troubles when it comes to modify and add child rows at the same time. I´m using the technique from the answer: stackoverflow.com/questions/5557829/....
The problem is in the following code:
public void EditReport(tbl_inspection inspection)
{
foreach (var roll in inspection.tbl_inspection_roll)
{
container.tbl_inspection_roll.Attach(roll);
container.ObjectStateManager.ChangeObjectState(roll, (roll.id_inspection_roll == 0) ? EntityState.Added : EntityState.Modified);
}
container.SaveChanges();
}
I always have at least 1 row to update. When I have 1 row to add, it works fine, the problem is when I try to add more than 1 row at the same time, shows the well-known error:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
Feels like I´m missing something here...
I think that you need to split off the modified from the added. In the question that you linked to Ladislav had the following code as an example of this:
if (myEntity.Id != 0)
{
context.MyEntities.Attach(myEntity);
context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
context.MyEntities.AddObject(myEntity);
}
context.SaveChanges();
I think that using Attach specifically, instead of using AddObject is what's causing the error.
EDIT: Try the following for the Attach part instead:
var r = new tbl_inspection_roll { id_inspection_roll = roll.id_inspection_roll };
container.tbl_inspection_roll.Attach(r);
container.Entry(r).CurrentValues.SetValues(roll);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With