问题描述
这是我的问题,所以我只希望允许用户仅更改/编辑其密码和用户名。
我给客户的原始模型是这个
public string IC { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username{ get; set; }
public string Password{ get; set; }
这是我的客户虚拟机
public string Username{ get; set; }
public string Password{ get; set; }
这是我的编辑功能控制器
public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
{
if (ModelState.IsValid)
{
db.Entry(customersVM ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customersVM );
}
view.cshtml
@Html.ValidationSummary(true,"",new { @class = "text-danger" })
@Html.HiddenFor(model => model.IC)
<div class="form-group">
@Html.LabelFor(model => model.Username,htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Username,new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Username,new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password,htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password,new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password,new { @class = "text-danger" })
</div>
</div>
因此,此虚拟机将使ModelState变为有效状态,该状态将直接进入数据库,但事实证明是发生了此类错误
system.invalidOperationException:'实体类型CustomerVM不是当前上下文模型的一部分。'
解决方法
为了编辑/更新记录,您需要首先识别该记录。就您而言,您的ViewModel
不是数据库所拥有的,而是问题中的第一个模型。因此,您需要先将viewModel映射到真实模型,然后再保存或获取现有记录,然后对其进行修改,然后在保存之前将其设置为已修改。
public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
{
if (ModelState.IsValid)
{
var existing = db.Customers.FirstOrDefault(x => x.Id == customersVM.Id);
if (existing != null)
{
existing.Username = customersVM.Username;
existing.Password = customerVM.Password;
db.Entry(existing ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(customersVM );
}