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
var word = ctx.Words.Where(a=>a.WordId == wordId).First();
ctx.DeleteObject(word);
ctx.SaveChanges();
2. Disconnected scenario: attach an existing entity and mark it as deleted
var word = new Word() { WordId = id };
ctx.Words.Attach(word);
ctx.DeleteObject(word);
ctx.SaveChanges();
The second approach will help you avoid un-necessary database round trip
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.