I am getting this error \"The object cannot be deleted because it was not found in the ObjectStateManager.\"
My code is:
protected MyEntities sql
Just a small clarification on the answer by Ladislav Mrnka (which should be the accepted answer).
If like me, you've got code in a format like this:
using (var context = new MyDataContext())
{
context.MyTableEntity.Remove(EntytyToRemove);
var nrOfObjectsChanged = context.SaveChanges();
}
..then this what you want to do:
using (var context = new MyDataContext())
{
// Note: Attatch to the entity:
context.MyTableEntity.Attach(EntityToRemove);
context.MyTableEntity.Remove(EntityToRemove);
var nrOfObjectsChanged = context.SaveChanges();
}
Perhaps this seems obvious, but it was not clear to me initially that it is necessary to specify the entity to attatch to, and not just the context.