Hi, I am developing simple task using different layers and everything is working fine but I have scenario where I need to insert to two tables when click on save ,one employee table and other employeeposition table. Here is my code.
In Service class
public void Update(EmployeeViewModel employeeViewModel)
{
Employee employee = new Employee()
{
EmployeeId = employeeViewModel.EmployeeId,
FirstName = employeeViewModel.FirstName,
LastName = employeeViewModel.LastName,
PhoneNumber = employeeViewModel.PhoneNumber,
Address = employeeViewModel.Address,
EmployeePositions = new List
{
new EmployeePosition
{
PositionId=employeeViewModel.PositionId,
EmployeeId=employeeViewModel.EmployeeId
}
}
};
if (employee == null)
throw new ArgumentNullException("Employee Update");
_employeeRepository.Update(employee);
_employeePositionRepository.UpdateCollection(employee.EmployeePositions);
}
In Repository Class
public void UpdateCollection(ICollection collection)
{
if (collection == null)
throw new ArgumentNullException("collection is null");
foreach (var item in collection)
{
DataContext.Entry(item).State = EntityState.Deleted;
}
this.DataContext.SaveChanges();
}
and COntroller class
[HttpGet]
public ActionResult Edit(int? id)
{
var employee = _employeeService.GetById((int)id);
if (employee == null) throw new ArgumentNullException("Employee Information Not Found");
return View(employee);
}
[HttpPost]
public ActionResult Edit(EmployeeViewModel employee)
{
_employeeService.Update(employee);
return RedirectToAction("View", "Employee");
}
Now when ever update happens I need to delete records in employeeposition table for that employeeid and insert it.
How can I do this