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?