正确的方法来更新从控制器编辑操作的实体? [英] Proper way to update entity from controller Edit action?

查看:150
本文介绍了正确的方法来更新从控制器编辑操作的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

控制器

首先,我尝试这样做:

[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);
}

错误在的SaveChanges抛出()

错误消息:存储更新,插入或删除语句影响行的
意想不到号( 0)。实体可能已被修改或
删除,因为实体被加载。刷新ObjectStateManager
项。

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."

我看了看 JournalEntry的实体,并注意到其JournalEntryId为0,而所有其他属性都设置正确。因此,我把它改成这样:

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?

推荐答案

其实,你可以重命名你的<$的 JournalEntryId 属性C $ C> JournalEntry的视图模式编号,然后默认的模型绑定会自动填充为你,这样你就不用写以下行:

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;

和您的第一个代码段将工作,因为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)

或修改 Html.BeginForm 声明,包括参数作为查询字符串参数:

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

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

这篇关于正确的方法来更新从控制器编辑操作的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆