Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

context.SaveChanges not working

My update method is not working in an ASP.NET MVC 3 application. I have used the following EF 4.1 code:

[HttpPost]
public ActionResult UpdateAccountDetails(Account account)
{
    if (ModelState.IsValid)
    {
        service.SaveAccount(account);
    }
}

and SaveAccount looks like this:

internal void SaveAccount(Account account) {         
    context.SaveChanges();
}
like image 413
DotnetSparrow Avatar asked Nov 08 '11 20:11

DotnetSparrow


4 Answers

internal void SaveAccount(Account account) {

    // Load current account from DB
    var accountInDb = context.Accounts.Single(a => a.Id == account.Id);

    // Update the properties
    context.Entry(accountInDb).CurrentValues.SetValues(account);

    // Save the changes
    context.SaveChanges();
}

Alternative:

internal void SaveAccount(Account account) {

    context.Entry(account).State = EntityState.Modified;
    context.SaveChanges();
}
like image 76
Slauma Avatar answered Nov 14 '22 10:11

Slauma


The problem here is that you're not accounting for the fact that Web pages are stateless. You probably pupulate your page with the account data returned from the database, but then the object is destroyed at the end of the request.

On postback, a new Acccount object is created by the model binder, but this one is not hooked up to the database, so your database context has no idea that it even exists. So when you call SaveChanges, nothing has changed as far as it is concerned.

You have to either get a new Account object from the database and update it's fields with the data from the model binder created Account, or attach the new account object to the database.

like image 42
Erik Funkenbusch Avatar answered Nov 14 '22 10:11

Erik Funkenbusch


This article should help

http://msdn.microsoft.com/en-us/library/bb896271.aspx

You may need to add context.Accounts.Attach(account); to reattach your entity to the context

like image 1
msmucker0527 Avatar answered Nov 14 '22 11:11

msmucker0527


You aren't making any changes, so there is really nothing to be saved. The simplest way may be doing the following:

internal void SaveAccount(Account account)
{
    context.Attach(account);
    ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(account);
    entry.SetModified();

    context.SaveChanges();
}
like image 1
Yakimych Avatar answered Nov 14 '22 11:11

Yakimych