这是我在Httpost中的Controllers编辑方法
[HttpPost]
public ActionResult Edit(Employee employee)
{
if (!ModelState.IsValid)
{
var department = db.Departments.ToList();
var viewModel = new EmployeeViewModel
{
Departments = department,
Employees = db.Employees.ToList()
};
return View("Index", viewModel);
}
db.Entry(employee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
此方法创建新数据而不是更新数据。
答案 0 :(得分:0)
问题是您试图直接根据操作参数更新Employee
实例,而不先寻找任何匹配记录,因此EF“不知道”是否应修改实体并将其状态视为{{1} }这一行:
EntityState.Added
您应该使用db.Entry(employee).State = EntityState.Modified;
或SingleOrDefault()
从FirstOrDefault()
属性获取匹配记录,更新所有必需的属性,然后将Id
实例附加到{{1} }实体并将其状态设置为Employee
:
Employees
相关问题:
Why does Entity Framework reinsert existing objects into my database?
Updating the Record with EntityState.Modified but its inserting the new row rather than update