ChrisCurrie
ChrisCurrie

Reputation: 1639

MVC 4, EF 5 SaveChanges does not update database

I'm relatively new to this but I'm still a little embarrassed as this really should be simple...

All I'm trying to do is update an existing row in a database table. I'm using EF (5 I believe) code first.

For MVC 3 I used this approach (which worked):

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

I've tried a few examples that I've found and although they don't error the database doesn't get updated...

[HttpPost]
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;
            db.SaveChanges();
        }

Upvotes: 1

Views: 11508

Answers (2)

ChrisCurrie
ChrisCurrie

Reputation: 1639

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();

Upvotes: 4

Niraj
Niraj

Reputation: 1842

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();
    }

Upvotes: 0

Related Questions