2011-03-10 64 views
1

我有一個嚴重的問題,我有一個唯一的鍵字段在數據庫中,我使用的是Oracle(Devart Provider)。EF 4.0和ObjectStateManager有問題(我認爲)

我第一次預成型體插入 - >(_objectSet.Add(entity))通過我的倉庫它的確定,

BTW:我使用的唯一的代碼模型和CTP5。

然後,如果我想再次插入它會激發一個錯誤,我有一個「唯一的鍵約束」,它也是正常的。

之後,無論我做什麼,它總是會拋出同樣的錯誤!

那是什麼和如何解決它?

預先感謝您。

+0

你應該澄清這是什麼意思:「之後,無論我做什麼,總是會拋出同樣的錯誤!」 – 2011-03-10 08:39:33

+0

你說得對,我很抱歉我改變了實體中的所有值(新實體) – IamStalker 2011-03-10 09:41:23

+0

你不能對新實體進行更改,因爲舊實體已被上下文跟蹤。將舊的值更改爲@zmurf在他的答案中所述。 – 2011-03-10 09:42:58

回答

0

答案很簡單,然後我想,我只需從上下文中抽取實體, 在我收到重複實體的異常或其上下文中存在任何異常之後,正確的方法是將實體和而已。

我從德維特的安德烈得到了這個答案。

1

您是否試圖使用相同的實體來添加(實體)?那麼你會得到這個錯誤。如果你想改變該實體的某些內容,只需執行諸如「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(); 

在這種情況下,它會嘗試插入已經跟蹤實體作爲新行具有相同的鍵,它會抱怨說,已經有一個上一行用相同的密鑰通過拋出「唯一鍵約束」錯誤。

+0

正如我上面向樓上的那個人所說的那樣,我做了這些改變,沒有任何改變。 – IamStalker 2011-03-10 09:42:11

+0

對不起,我可能被誤解了,問題就更深了。 我已經爲自己設定了一個唯一的約束,如果有人把第一次ef4響應的數據例如「personid」放入(主鍵或唯一鍵),那麼確定您對此列有唯一的鍵約束,但如果我改變一個不同的「personid」它仍然說同樣的事情,這是工作,直到第一次「唯一鍵約束」被拋出後,它停止工作。我認爲也許Devart供應商持有緩存但他們正在檢查它,但直到那時我還在等待,這是錯誤的。 – IamStalker 2011-03-11 22:15:56

+0

啊..是的,我完全誤解了這個問題。在這種情況下,您必須(如您在自己的答案中所述)分離實體。 – zmurf 2011-03-21 08:18:30

0

@IamStalker,你能否指定一些關於錯誤的更多細節?
如果可能,請在這裏發帖或send us您使用的示例代碼添加和更新實體,或者使用您的DB對象POCO代碼甚至是一個小型測試項目。

+0

yescaurse我會馬上去做 – IamStalker 2011-03-10 12:00:46

+0

如果我做了一些事情,我已經給你發了一個鏈接。 – IamStalker 2011-03-10 12:08:00

+0

三天前,我已經發送給Devart支持一個包含該項目示例的電子郵件,但沒有收到任何答覆,爲什麼? – IamStalker 2011-03-13 20:15:10