How I can delete an entity using EF5? I’m getting this error:
The object cannot be deleted because it was not found in the ObjectStateManager.
when I try to call .Remove on my DbSet. After googling I tried that
mycontext.Attach(entity)
mycontext.Remove(entity)
But in this way I get:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
So, is it or not in ObjectStateManager?! 🙂
My entity is like that:
[Table("Words")]
public class Word : IWord
{
[Key, Required]
public int WordId { get; set; }
[Required, StringLength(50)]
public string Tag { get; set; }
//Foreign Key
public int VocabularyId { get; set; }
//Navigation
public virtual Vocabulary Vocabulary { get; set; }
public virtual Language Language { get; set; }
public virtual List<Translation> Translations { get; set; }
}
You can consider 2 scenario:
1. Connected scenario: you load the entity from database and mark it as deleted
2. Disconnected scenario: attach an existing entity and mark it as deleted
The second approach will help you avoid un-necessary database round trip