我如何在 Asp.net MVC 中使用视图模型更新多个表



>员工模型

public class Employee
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public virtual Department Departments { get; set; }
public int DepartmentID { get; set; }
}

部门模型

public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
}

查看部门和员工的模型

public class EDViewModel
{
public int ID { get; set; }
public int EmployeeID { get; set; }
public string Name { get; set; }
public Department Departments { get; set; }
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
}

现在我想用单个视图更新两个表。

控制器

public ActionResult Edit(int?id)
{
// write some code for update both table at once time
}

后法

[HttpPost]
public ActionResult Edit(EDViewModel Emodel)
{
var user = db.Employees.Where(c => c.Employee_Id == Emodel.Employee_Id).FirstOrDefault();
user.UserName = Emodel.UserName;
user.ProfilePicture = Emodel.ProfilePicture;
db.Entry(user).State = EntityState.Modified;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Home");
}

但在这种方法中,只更新员工记录而不是部门

经过多次搜索,我终于得到了一个可靠的解决方案 希望您喜欢或改进这一点。

控制器

public ActionResult Edit(int? id)
{
MYDb db = new MYDb();
var user = db.Employees.Where(c => c.Employee_Id == Emodel.Employee_Id).FirstOrDefault();
if (user != null)
{
var vm = new EDViewModel { Employee_id = user.Employee_id, departmentName = user.departmentName };
if (user.department != null)
{
user.Departmet_id = vm.Departments.Departmet_id;
user.DepartmentName = vm.Departments.DepartmentName;
user.Employee_id = vm.employee_id;
user.employeeName = vm.employeeName;
}
return View(user);
}
return Content("Invalid Id");
}
[HttpPost]
public ActionResult Edit(EDViewModel Emodel)
{
var user = db.Employees.Where(c => c.Employee_Id == Emodel.Employee_Id).FirstOrDefault();
user.EmployeeId = Emodel.EmployeeId;
user.EmployeeName= Emodel.EmployeeName;
user.DepartmentName= Emodel.Departmt.DepartmentName;
// Just remove this line
//  db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Home");
}

它对我有用 只需删除此

db.Entry(user).State = EntityState.Modified;

如果我们不删除此实体验证发生

相关内容

  • 没有找到相关文章

最新更新