同じエンティティで .Add(entity) を実行しようとしていますか? 次に、そのエラーが発生します。そのエンティティで何かを変更したい場合は、「entity.rowname = value」のような変更を行い、.Add(entity) を実行せずに保存すると、問題なく動作するはずです。
普段のやり方はこんな感じです。
データベースに新しい行を作成します。
Entity entity = new Entity();
entity.value = value;
db.Entity.AddObject(entity);
db.SaveChanges();
行を取得して編集します。
var entity = db.Entity.SingleOrDefault(e => e.value == value);
entity.value = newValue;
db.SaveChanges();
このようなことも問題なくできます
Entity entity = new Entity(); //creating a new Entity
entity.value = 1; //Setting a value on the new Entity
db.Entity.AddObject(entity); //Adding the Entity to the context
db.SaveChanges(); //Saving the record to the database
entity = db.Entity.SingleOrDefault(e => e.value == 2); //retrieving another, already added record
entity.value = 5; //Changing the value on the retrieved record
db.SaveChanges(); //Saving the change to the database
entity = new Entity(); //creating yet another new Entity
entity.value = 8; //setting the value on the second new Entity
db.Entity.AddObject(entity); //adding the Entity to the context
db.SaveChanges(); //Saving the second new Entity to the database
あなたはこのようにすることはできません
var entity = db.Entity.SingleOrDefault(e => e.value == value);
entity.value = newValue;
db.Entity.AddObject(entity); //WRONG!
db.SaveChanges();
またはこれ
Entity entity = new Entity();
entity.value = value;
db.Entity.AddObject(entity);
db.SaveChanges();
entity.value = newValue;
db.Entity.AddObject(entity); //WRONG!
db.SaveChanges();
この場合、既に追跡されているエンティティを同じキーを持つ新しい行として挿入しようとし、「一意のキー制約」エラーをスローして、同じキーを持つ前の行が既に存在することを訴えます。