Proper way to update entity from controller Edit action?

坚强是说给别人听的谎言 提交于 2019-12-20 05:33:13

问题


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?


回答1:


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)
{
    ...        
}


来源:https://stackoverflow.com/questions/9775503/proper-way-to-update-entity-from-controller-edit-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!