【问题标题】:An object with the same key already exists in the ObjectStateManagerObjectStateManager 中已存在具有相同键的对象
【发布时间】:2011-12-27 21:46:45
【问题描述】:

任何人都可以帮助我处理此代码我收到此错误消息:

“/”应用程序中的服务器错误。 ObjectStateManager 中已存在具有相同键的对象。现有对象处于已修改状态。只有处于添加状态的对象才能再次添加到 ObjectStateManager。 说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.InvalidOperationException:ObjectStateManager 中已存在具有相同键的对象。现有对象处于已修改状态。只有处于添加状态的对象才能再次添加到 ObjectStateManager 中。

来源错误:

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

源文件:C:\Users\dell\Documents\Visual Studio 2010\Projects\MvcApplication3\MvcApplication3\Models\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();              
    }   
}

【问题讨论】:

  • 你应该使用泛型集合。

标签: c# asp.net-mvc-3 entity-framework


【解决方案1】:

您尝试在每次循环时添加相同的 Twitter 实例。

您需要在每次迭代中(在循环体内)创建一个新实例。

【讨论】:

    【解决方案2】:

    @Slaks 他不需要释放每个实例,他是否会遇到堆栈溢出错误,请原谅双关语..LOL

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

    // tw.Dispose() 或 tw = null 如果它没有实现 IDisposable

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      相关资源
      最近更新 更多