如何使用EF5删除实体?我得到了这个错误:
The object cannot be deleted because it was not found in the ObjectStateManager.当我尝试在我的DbSet上调用.Remove时。在谷歌搜索之后,我试过了
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; }
}发布于 2013-01-27 23:42:58
您可以考虑两种场景:
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();第二种方法将帮助您避免不必要的数据库往返
https://stackoverflow.com/questions/14548874
复制相似问题