none
在WCF下,调用EF的Update方法出现 ”ObjectStateManager 中已存在具有同一键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象“问题 RRS feed

  • 问题

  • 不用WCF修改正常

     [TestCase]
            public void AreaService_TestModify()
            {
                IAreaService service = IoC.Resolve<IAreaService>();
     
                if (area != null)
                {
                  
                    area.Code = "city2";
                  
                    //area.ModifiedAt = DateTime.Now;
                    service.Save(area);
                }

            }

    使用WCF调用则出现上述错误 {"ObjectStateManager 中已存在具有同一键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。"}

     [TestCase]

            public void AreaService_Get_Test()
            {
               
                IAreaService s = ServiceProxyFactory.Create<IAreaService>("areaservice");
                Area area = s.Get(staticid);
                area.City = "modified";
                s.Save(area);
                Assert.IsTrue(area.ID == staticid);
               
            }

     

    修改方法

     public virtual void Update(T entityToUpdate)
            {
                     dbSet.Attach(entityToUpdate);
                     context.Entry(entityToUpdate).State = EntityState.Modified;
            }

    2011年12月12日 16:37

答案

  • 是Attach方法报的错

    ---------------------------

    If more than one entity of a particular type has the same key value, the Entity Framework will throw an exception. To avoid getting the exception, use the AddObject method to attach the detached objects and then change the state appropriately. http://msdn.microsoft.com/en-us/library/bb896271.aspx

    ---------------------------


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年12月21日 9:01
    版主