【发布时间】:2016-09-03 12:42:26
【问题描述】:
需要
在员工表中保存姓名并保存所有课程
在编辑 [HTTPPOST] 中单击提交按钮时在员工课程表中
问题总结
提交按钮只保存更改并删除之前存在的数据
问题详情
当点击编辑帖子中的提交按钮时,课程将保存
点击提交前我添加或选择的课程将保存
但是员工之前的课程会被删除
示例
1-我添加员工姓名MEDO有课程c++
2-in 编辑视图显示 c++
3-如果我在编辑视图中添加 python 然后点击提交它必须有两个课程
c++和python
4- 仅当再次为该员工打开编辑时才会向我显示 python
它保存选择的课程,但课程在删除之前存在
问题图片
下面的图片显示了所有细节
SAVE all courses in employeecourse table
代码
public class EditEmployeeVm
{
public int Id { set; get; }
public string Name { get; set; }
public List<SelectListItem> Courses { get; set; }
public int[] CourseIds { set; get; }
public List<CourseVm> ExistingCourses { set; get; }
}
public class CourseVm
{
public int Id { set; get; }
public string Name { set; get; }
}
in edit function get i pass data to edit view
public ActionResult Edit(int id)
{
var vm = new EditEmployeeVm { Id = id };
var emp = db.Employees.FirstOrDefault(f => f.Id == id);
vm.Name = emp.Name;
vm.ExistingCourses = db.EmployeeCourses
.Where(g => g.EmployeeId == id)
.Select(f => new CourseVm
{
Id = f.Id,
Name = f.Course.CourseName
}).ToList();
vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();
vm.Courses = db.Courses.Select(f => new SelectListItem
{
Value = f.Id.ToString(),
Text = f.CourseName
}).ToList();
return View(vm);
}
[HttpPost]
public ActionResult Edit(EditEmployeeVm model)
{
var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);
foreach (EmployeeCourse eec in emp.EmployeeCourses.ToList())
{
var ec = db.EmployeeCourses.Find(eec.Id);
db.EmployeeCourses.Remove(ec);
db.SaveChanges();
}
foreach (var couseid in model.CourseIds)
{
db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });
db.SaveChanges();
}
return View();
}
更新
[HttpPost]
public ActionResult Edit(EditEmployeeVm model)
{
**//i need to save name employee changes in employee table and all courses in emloyeecourse table
//what is wrong here**
var emp = db.Employees
.Include(e => e.EmployeeCourses)
.FirstOrDefault(f => f.Id == model.Id);
foreach (var eec in emp.EmployeeCourses.ToList())
{
db.EmployeeCourses.Remove(eec);
}
foreach (var couseid in model.CourseIds)
{
db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });
}
db.SaveChanges();
return View();
}
【问题讨论】:
标签: entity-framework asp.net-mvc-4 linq-to-entities entity-framework-6