None of the above answers quite covered my situation and the solution to it.
Code where the error was thrown in MVC5 controller:
if (ModelState.IsValid)
{
db.Entry(object).State = EntityState.Modified;
db.SaveChanges(); // line that threw exception
return RedirectToAction("Index");
}
I received this exception when I was saving an object off an Edit view. The reason it threw it was because when I went back to save it, I had modified the properties that formed the primary key on the object. Thus, setting its state to Modified didn't make any sense to EF - it was a new entry, not a previously saved one.
You can solve this by either A) modifying the save call to Add the object, or B) just don't change the primary key on edit. I did B).