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

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

2番目のアプローチは、不必要なデータベースのラウンドトリップを回避するのに役立ちます

于 2013-01-27T15:42:57.657 に答える