只更新需要的字段 mvc EF

update only needed field mvc EF

我的代码是这样的 型号

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 字段,但是当我 运行 代码时 table 中的所有字段都是 updated.For 哪些列我没有添加值获取更新为 null。谁能指出我在这里做错了什么?

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

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