Reputation: 1673
I'm using MVC 2 with EF4. Creating or deleting objects works but update doesn't. I have read lot and lot tutorials / questions on StackOverflow, but I haven't found a real WORKING code to use in my "Edit" method.
[HttpPost]
public ActionResult Edit(int id, Account model)
{
try
{
Account accountEdited = accountRepository.Get(id);
// Working code to update "accountEdited" with "model"'s values ???
accountRepository.Save();
return RedirectToAction("Details", new { id = id });
}
catch (Exception ex)
{
return View();
}
}
I'm using EntityFramework with WCF Data Service
Upvotes: 1
Views: 1831
Reputation: 73112
This is what I do:
[HttpPost]
public ActionResult Edit(int id, Account model)
{
try
{
Account accountEdited = accountRepository.Get(id);
TryUpdateModel(accountEdited);
ctx.SaveChanges();
return RedirectToAction("Details", new { id = id });
}
catch (Exception ex)
{
return View();
}
}
The initial call to the repository will ensure the entity is in the graph, in an Unmodified state. MVC's built in TryUpdateModel
method will then merge the two objects together (the accountEdited
object, and the form post data that has been model bound).
This will result in the entity being in a Modified
state.
Simply calling SaveChanges()
on the object context will then push the changes to the database.
I have dabbled in techniques such as the "stub technique" but it introduced a world of pain (mainly to do with relationships), so this is the easiest approach, and works well.
Upvotes: 3
Reputation: 38503
You have your real EF work abstracted from you code you posted. Here is the simplest EF save:
public void Save(Account account)
{
using (DBContext ctx= new DBContext ())
{
ctx.Attach(account);
ctx.SaveChanges();
}
}
You only need to attach the object if it was obtained in another context. If not you can do it like:
public void Save(int AccountID)
{
using (DBContext ctx= new DBContext ())
{
Account account = ctx.Account.Single(a => a.ID == AccountID)
account.property = somepropchange;
ctx.SaveChanges();
}
}
Upvotes: 1