在编辑方法中,更新数据创建新数据,而不是mvc5

时间:2019-01-29 18:13:53

标签: asp.net-mvc-5

这是我在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");
    }

此方法创建新数据而不是更新数据。

1 个答案:

答案 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