O.O
O.O

Reputation: 11287

Proper way to update entity from controller Edit action?

Controller

First I tried this:

[HttpPost]
public ActionResult Edit(JournalEntry journalentry)
{
    if (ModelState.IsValid)
    {
        db.Entry(journalentry).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index", new { id = journalentry.Journal.JournalId });
    }
    return View(journalentry);
}

Error was thrown in SaveChanges():

Error Message: "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."

I looked at the journalentry entity and noticed that its JournalEntryId was 0, but all the other properties were set correctly. Therefore, I changed it to this:

[HttpPost]
public ActionResult Edit(int id, JournalEntry journalentry)
{
    if (ModelState.IsValid)
    {
        journalentry.JournalEntryId = id;
        db.Entry(journalentry).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index", new { id = journalentry.Journal.JournalId });
    }
    return View(journalentry);
}

Everything looked to save correctly, but is this the correct way to save the entity?

Upvotes: 1

Views: 2791

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Actually you could rename the JournalEntryId property in your JournalEntry view model to Id and then the default model binder will automatically populate it for you so that you don't have to write the following line:

journalentry.JournalEntryId = id;

and your first code snippet will work because the Id property will be populated with the value from the route.

Or if for some reason you cannot rename the property on your view model (actually I know the reason => you are not using any view models at all but you are passing your domain entities directly to the view which is bad but subject to another question), you could use a hidden field in your form:

@Html.HiddenFor(model => model.JournalEntryId)

or modify your Html.BeginForm declaration to include the parameter as query string argument:

@Html.BeginForm("Edit", "SomeController", new { JournalEntryId = Model.JournalEntryId }, FormMethod.Post)
{
    ...        
}

Upvotes: 2

Related Questions