2011-12-27 61 views
0

任何人都可以幫我這個代碼,我收到此錯誤信息:一個使用相同的密鑰對象已存在於ObjectStateManager

Server Error in '/' Application. An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.

源錯誤:

Line 90: public void AddToTwitter(Twitter twitter) 
Line 91: { 
Line 92:  base.AddObject("Twitter", twitter); 
Line 93: } 

源文件:C: \用戶\ DELL \文檔\ Visual Studio 2010的\項目\ MvcApplication3 \ MvcApplication3 \型號\ TwitterEntity.Designer.cs線:92

代碼:

Models.TwitterEntities entity = new Models.TwitterEntities(); 
Models.Twitter tw = new Models.Twitter(); 

foreach (Hashtable item in (ArrayList)hs["results"]) 
{     
    foreach (DictionaryEntry subitem in item) 
    { 
     if (subitem.Key.ToString() == "from_user") 
     { 
      tw.from_user = (string)subitem.Value; 
      Response.Write("<br>" + (string)subitem.Value); 
      entity.AddToTwitter(tw); 
     } 
     if (subitem.Key.ToString() == "to_user") 
     { 
      tw.to_user = (string)subitem.Value; 
      Response.Write("<br>" + (string)subitem.Value); 
      entity.AddToTwitter(tw); 
     } 
     entity.SaveChanges();    
    } 
} 
+1

您應該使用泛型集合。 – SLaks 2011-12-27 21:49:08

回答

3

您試圖在每次通過循環時添加相同的Twitter實例。

您需要在每次迭代(在循環體內)中創建一個新實例。

+0

yeeep謝謝:) – kankele 2011-12-27 21:51:12

0

@Slaks不會,他需要釋放每個實例也將他碰上一個計算器錯誤原諒pun..LOL

Models.Twitter tw = new Models.Twitter(); 
// do code... 

// tw.Dispose()或TW = NULL如果它不實現IDisposable

+0

這是完全錯誤的。這不是C++。 – SLaks 2011-12-28 01:39:53

相關問題