您是否試圖使用相同的實體來添加(實體)?那麼你會得到這個錯誤。如果你想改變該實體的某些內容,只需執行諸如「entity.rowname = value」的更改,然後保存而不嘗試執行.Add(實體),它應該工作得很好。
你通常如何做到這一點是這樣的。
在數據庫中創建新行:
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
您可以NOT是這樣做的
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();
在這種情況下,它會嘗試插入已經跟蹤實體作爲新行具有相同的鍵,它會抱怨說,已經有一個上一行用相同的密鑰通過拋出「唯一鍵約束」錯誤。
你應該澄清這是什麼意思:「之後,無論我做什麼,總是會拋出同樣的錯誤!」 – 2011-03-10 08:39:33
你說得對,我很抱歉我改變了實體中的所有值(新實體) – IamStalker 2011-03-10 09:41:23
你不能對新實體進行更改,因爲舊實體已被上下文跟蹤。將舊的值更改爲@zmurf在他的答案中所述。 – 2011-03-10 09:42:58