仅更新所需的字段mvc EF

时间:2015-01-21 10:35:06

标签: c# asp.net-mvc entity-framework razor

我的代码是这样的 模型

public class Department
{
    public int DepartmentID { get; set; }
    public string Name { get; set; }
    public bool Status { get; set; } //no appointments when false
    public DateTime CreatedDate { get; set; }
    public int CreatedUserId
    {
        get { return ((SystemUser) HttpContext.Current.Session["CurrentUser"]).SystemUserID; }
    }

}

控制器

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include="DepartmentID,Name,CreatedUser,CreatedDate")] Department department)
    {
        if (ModelState.IsValid)
        {
            db.Entry(department).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(department);
    }

查看(编辑)

    @model DiagnosisApp.Models.Department

@using (Html.BeginForm())
{
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.DepartmentID)
        @Html.TextBoxFor(model => model.Name, new { @class = "form-control", @placeholder = "Enter Department Name" })
        <button type="submit" value="Save" >Save</button>

}

正如您在视图中看到的,我只想更新Name字段,但是当我运行代码时,表中的所有字段都会更新。我没有添加值的列会更新为null。谁能指出我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为你做错了就忘了将实体附加到上下文中。当然,模型对象没有所有属性。因此,它的模型绑定器为那些未在UI中呈现的属性发送默认值。

           if (ModelState.IsValid)
            {
                db.Department.Attach(department);
                db.Entry(department).Property(x => x.name).IsModified = true;
                db.SaveChanges();
                return RedirectToAction("Index");
            }