1

I have two entities as follows:

 public class Package
     {
            public int PackageId { get; set; }
            public int BusinessId { get; set; }

             public string Name { get; set; }
     }

And

   public class Business
     {


    public int BusinessId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    }

I want to edit the Package and update the related Business entity. I’ve been trying the following:

    [HttpPost]
    public ActionResult Edit(Package package)
    {

        if (ModelState.IsValid)
        {

                db.Packages.Attach(new Package { PackageId=package.PackageId
       });


                db.Entry(package).State = EntityState.Modified;

                db.SaveChanges();


            return RedirectToAction("Index");
        }
        ViewBag.GenreId = new SelectList(db.Businesses , "BusinessId", "Name", package.BusinessId);
        return View(package);
    }

The code stops here with this message:

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

I’ve been trying the example like the one here... http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx... but I’m not sure what I’m doing wrong.

How do I update the entity with the foreign key?

CloudyKooper
  • 727
  • 3
  • 19
  • 47
  • This question is quite similar to this question posted 2 months ago. Kindly look at this.. http://stackoverflow.com/questions/13311652/object-with-same-key-already-exists-in-objectstatemanager – bot Jan 25 '13 at 10:01

1 Answers1

0
[HttpPost]
public ActionResult Edit(int packageId)
{

    var package = db.Packages.FirstOrDefault(x=>x.Id == packageId);
    if(TryUpdateModel(package))
    {
        ...
        db.SaveChanges();
    }
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117