1

如何使用 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; }

}
4

1 回答 1

1

您可以考虑两种情况:

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();

第二种方法将帮助您避免不必要的数据库往返

于 2013-01-27T15:42:57.657 回答