MVC 4, EF 5 SaveChanges does not update database

asp.net-mvc asp.net-mvc-4 c# entity-framework

Question

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();
        }
1
1
2/7/2013 10:46:53 PM

Accepted Answer

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();
4
5/23/2017 11:58:39 AM

Popular Answer

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


Related Questions





Related

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