MVC 4, EF 5 SaveChanges does not update database

ChrisCurrie

I have managed to resolve this issue using the following code mentioned in this SO post which shows how to save only the new values:

db.Entry(activeCitizen).CurrentValues.SetValues(citizenDetails.ActiveCitizen);

Note, I experienced the error: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"

This SO post helped me overcome that issue.

The final code was therefore:

var currentCitizen = db.ActiveCitizen.Find(citizenDetails.ActiveCitizen.ID);
db.Entry(currentCitizen).CurrentValues.SetValues(citizenDetails.ActiveCitizen);
db.SaveChanges();

Try This

[HttpPost]
public ActionResult Edit(CitizenEntryViewModel citizenDetails)
{
    ActiveCitizen activeCitizen = db.ActiveCitizen.SingleOrDefault(m => m.ID == citizenDetails.ActiveCitizen.ID);

    if (activeCitizen != null)
    {
        UpdateModel(activeCitizen);
        db.SaveChanges();
    }