如何使用EF5删除实体?我收到此错误:
The object cannot be deleted because it was not found in the ObjectStateManager.
当我尝试呼叫时。删除我的DbSet。谷歌搜索后我尝试了
mycontext.Attach(entity)
mycontext.Remove(entity)
但是这样我得到了:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
那么,它是否在ObjectStateManager中?! :)
我的实体是这样的:
[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; }
}
答案 0 :(得分:1)
您可以考虑2个方案:
<强> 1。已连接方案:您从数据库加载实体并将其标记为已删除
var word = ctx.Words.Where(a=>a.WordId == wordId).First();
ctx.DeleteObject(word);
ctx.SaveChanges();
<强> 2。已断开连接的方案:附加现有实体并将其标记为已删除
var word = new Word() { WordId = id };
ctx.Words.Attach(word);
ctx.DeleteObject(word);
ctx.SaveChanges();
第二种方法将帮助您避免不必要的数据库往返