The object cannot be deleted because it was not found in the ObjectStateManager

Sami picture Sami · Oct 17, 2011 · Viewed 90.2k times · Source

I am getting this error "The object cannot be deleted because it was not found in the ObjectStateManager."

My code is:

    protected MyEntities sqlEntities;

    public virtual void Delete(TEntity entity)
    {
        System.Type t = typeof(TEntity);
        sqlEntities.DeleteObject(entity);
        sqlEntities.SaveChanges();
    }

Answer

Ladislav Mrnka picture Ladislav Mrnka · Oct 17, 2011

It means that entity is not attached (it was not loaded by the same context instance). Try this:

protected MyEntities sqlEntities;

public virtual void Delete(TEntity entity)
{
    sqlEntities.Attach(entity);
    sqlEntities.DeleteObject(entity);
    sqlEntities.SaveChanges();
}