Tuizi
Tuizi

Reputation: 1673

How to save change with MVC 2 en EF 4?

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

Answers (2)

RPM1984
RPM1984

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

Dustin Laine
Dustin Laine

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

Related Questions