更新 EF4 实体上的单个属性,而无需隐藏字段

2023-12-02

我正在使用 EF4(Db First),并且我有一个具有许多不可为空属性的实体。

在编辑表单 (Razor/MVC3) 中,我希望仅允许编辑其中一个属性,而不允许编辑其他属性。

为了让它发挥作用,我必须把@Html.HiddenFor(...)我的每个其他属性的语句不能为空,否则我会在 SaveChanges() 上收到错误。

有没有一种简单的方法可以将 ID 隐藏在视图上,可以编辑的属性,然后仅更新该属性?


在这种情况下,您需要做的就是将您正在编辑的实体的 ID 作为隐藏字段以及您实际想要编辑的属性的文本字段包含在内:

@using (Html.BeginForm())
{
    @Html.HiddenFor(x => x.ID)
    @Html.EditorFor(x => x.PropertyYouWannaEdit)
    <button type="submit">Update</button>
}

然后在相应的控制器操作中,您可以从数据库中检索需要编辑的实体,更新需要编辑的属性的值并保存更改。

[HttpPost]
public ActionResult Update(SomeEntity model)
{
    SomeEntity entityToEdit = db.GetEntity(model.ID);
    entityToEdit.PropertyYouWannaEdit = model.PropertyYouWannaEdit;
    db.Update(entityToEdit);
    return RedirectToAction("Success");
}

但就我个人而言,我会使用视图模型自动映射器来处理这种情况。因此,我首先设计一个代表视图要求的视图模型,并包含仅需要编辑的属性:

public class MyEntityViewModel
{
    public int ID { get; set; }
    public string Property1ToBeEdited { get; set; }
    public string Property2ToBeEdited { get; set; }
    ...
}

然后就有相应的视图:

@model MyEntityViewModel
@using (Html.BeginForm())
{
    @Html.HiddenFor(x => x.ID)

    @Html.EditorFor(x => x.Property1ToBeEdited)
    @Html.EditorFor(x => x.Property2ToBeEdited)
    ...

    <button type="submit">Update</button>
}

最后是 2 个控制器操作(GET 和 POST):

public ActionResult Update(int id)
{
    // Fetch the domain model that we want to be edited from db
    SomeEntity domainModel = db.GetEntity(id);

    // map the domain model to a view model
    MyEntityViewModel viewModel = Mapper.Map<SomeEntity, MyEntityViewModel>(domainModel);

    // pass the view model to the view
    return View(viewModel);
}

[HttpPost]
public ActionResult Update(MyEntityViewModel model)
{
    if (!ModelState.IsValid)
    {
        // validation failed => redisplay view so that the user can fix the errors
        return View(model);
    }

    // fetch the domain entity that needs to be edited:
    SomeEntity entityToEdit = db.GetEntity(model.ID);

    // update only the properties that were part of the view model,
    // leaving the others intact
    Mapper.Map<MyEntityViewModel, SomeEntity>(model, entityToEdit);

    // persist the domain model
    db.Update(entityToEdit);

    // we are done   
    return RedirectToAction("Success");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更新 EF4 实体上的单个属性,而无需隐藏字段 的相关文章

随机推荐