MVC 4, EF 5 SaveChanges does not update database c# entity-framework


Even though I'm still learning, I feel a little humiliated because this really ought to be easy.

Simply updating an existing row in a database table is all I'm attempting to do. I'm using EF (5, I think) code first.

I followed this strategy with MVC 3 and it worked:

ReportCommon reportcommon = db.ReportCommon.Single(r => r.ReportCommonId == id);
reportcommon.IP = StaticUtilities.GetIPAddress();
db.ObjectStateManager.ChangeObjectState(reportcommon, EntityState.Modified);

Although I've tried a number of the examples I've discovered, the database isn't changed despite the absence of errors.

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

        if (activeCitizen != null)
            citizenDetails.ActiveCitizen.CitizenUpdatedRecordOn = DateTime.Now;
            // Fields we don't edit but still need to pass back
            citizenDetails.ActiveCitizen.PublicID = activeCitizen.PublicID;
            citizenDetails.ActiveCitizen.IsKIN = activeCitizen.IsKIN;
            activeCitizen = citizenDetails.ActiveCitizen;
2/7/2013 10:46:53 PM

Accepted Answer

The following code, which demonstrates how to save only the changed values, helped me to overcome this problem:


Note that I ran into the problem: "In the ObjectStateManager, an object with the identical key already exists. Multiple objects cannot be tracked by the ObjectStateManager using the same key."

I was able to solve that problem thanks to This SO article.

Therefore, the final code was:

var currentCitizen = db.ActiveCitizen.Find(citizenDetails.ActiveCitizen.ID);
5/23/2017 11:58:39 AM

Popular Answer


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow