2011-12-27 92 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

相关问题