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();
}
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();
}
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.
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
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With