Entity Framework - An object with the same key already exists in the ObjectStateManager

Posted by Justin on Stack Overflow See other posts from Stack Overflow or by Justin
Published on 2010-06-11T22:11:39Z Indexed on 2010/06/11 23:33 UTC
Read the original article Hit count: 1667

Filed under:

Hey all,

I'm trying to update a detached entity in .NET 4 EF:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(Developer developer)
        {
            developer.UpdateDate = DateTime.Now;
            if (developer.DeveloperID == 0)
            {//inserting new developer.
                DataContext.DeveloperData.Insert(developer);
            }
            else
            {//attaching existing developer.
                DataContext.DeveloperData.Attach(developer);
            }
            //save changes.
            DataContext.SaveChanges();
            //redirect to developer list.
            return RedirectToAction("Index");
        }

public static void Attach(Developer developer)
            {
                var d = new Developer { DeveloperID = developer.DeveloperID };
                db.Developers.Attach(d);
                db.Developers.ApplyCurrentValues(developer);
            }

However, this gives the following error:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Anyone know what I'm missing?

Thanks, Justin

© Stack Overflow or respective owner

Related posts about entity-framework