I am getting this error \"The object cannot be deleted because it was not found in the ObjectStateManager.\"
My code is:
protected MyEntities sql
I got this problem and solve it. Just copy below code:
sqlEntities.Attach(entity);
sqlEntities.Remove(entity);
sqlEntities.SaveChanges();
In case none of the above worked, you may try this solution:
context.Entry(yourObject).State = System.Data.Entity.EntityState.Deleted;
context.SaveChanges();
You can write this code:
var x=yourquery.FirstOrDefault();
sqlEntities.DeleteObject(x);
sqlEntities.SaveChanges();
Make sure the model passing into Remove(Entity) is exactly same as the database record.
Some times its possible to pass the model with out some fields like Id or Date. keep those into @html.Hiddenfor if you posting as form.
Best way is to pass the ID and get the entity using Find(Id) method and pass that to Remove(Entity)
Hope this helps someone.